AdityaTS AdityaTS - 1 month ago 10
Java Question

How better can you rewrite these lambdas?

Consider the following class

class Person {

private String firstName;
private String lastName;
private int age;
private Address address;

//Assume getters are also available

}


lambda #1 : Filter persons of a specific age

public List<Person> getPersonsOfAge(int age) {
List<Person> persons= fillPersonsInfo();
persons.stream().fiter(person -> person.getAge() == 21).collect(Collectors.toList());
}


lambda #2 : Filter persons with a specific last name

public List<Person> getPersonsAboveAge(String name) {
List<Person> persons= fillPersonsInfo();
persons.stream().fiter(person -> person.getLastName().equals(name)).collect(Collectors.toList());
}


lambda #2 : Filter persons living at the given address

public List<Person> getPersonsAboveAge(Address address) {
List<Person> persons= fillPersonsInfo();
persons.stream().filter(person -> person.getAddress().equals(address)).collect(Collectors.toList());
}


How compact can you make these lambdas? Can you reduce all the three lambdas to a single function reference?

Answer

You can have a helper method that all your other methods call, and pass in a filter for each type of method

 private List<Person> filterPeople(Predicate<Person> filter){
     List<Person> persons= fillPersonsInfo();
     return persons.stream()
           .filter(filter)
           .collect(toList());
 }

 public List<Person> getPeopleOfAge(int age){
     return filterPeople(person -> person.getAge == age);
 }

 public List<Person> getPeopleOfName(String name){
     return filterPeople(person -> person.getName().equals(name));
 }
Comments