AdityaTS AdityaTS - 2 months ago 19
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(); -> 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(); -> 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(); -> 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?


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();

 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));