Java Reference
In-Depth Information
public class FunctionUtilTest {
public static void main(String[] args) {
List<Person> list = Person.getPersons();
// Use the forEach() method to print each person in the list
System.out.println("Original list of persons:");
FunctionUtil.forEach(list, p -> System.out.println(p));
// Filter only males
List<Person> maleList = FunctionUtil.filter(list, p -> p.getGender() == MALE);
System.out.println("\nMales only:");
FunctionUtil.forEach(maleList, p -> System.out.println(p));
// Map each person to his/her year of birth
List<Integer> dobYearList = FunctionUtil.map(list, p -> p.getDob().getYear());
System.out.println("\nPersons mapped to year of their birth:");
FunctionUtil.forEach(dobYearList, year -> System.out.println(year));
// Apply an action to each person in the list
// Add one year to each male's dob
FunctionUtil.forEach(maleList, p -> p.setDob(p.getDob().plusYears(1)));
System.out.println("\nMales only after ading 1 year to DOB:");
FunctionUtil.forEach(maleList, p -> System.out.println(p));
}
}
Original list of persons:
John Jacobs, MALE, 1975-01-20
Wally Inman, MALE, 1965-09-12
Donna Jacobs, FEMALE, 1970-09-12
Males only:
John Jacobs, MALE, 1975-01-20
Wally Inman, MALE, 1965-09-12
Persons mapped to year of their birth:
1975
1965
1970
Males only after ading 1 year to DOB:
John Jacobs, MALE, 1976-01-20
Wally Inman, MALE, 1966-09-12
The program gets a list of persons, applies a filter to the list to get a list of only males, maps persons to the year of
their birth, and adds one year to each male's date of birth. It performs each of these actions using lambda expressions.
Note the conciseness of the code; it uses only one line of code to perform each action. Most notable is the use of the
Search WWH ::




Custom Search