Raskill
Raskill

Reputation: 175

Conditional method call in the map method java 8

Persons = personDao.getFileInformation(filePath)
                    .skip(1)
                    .map(this::getPerson)
                    .filter(person -> person != null)
                    .collect(Collectors.toList());

getFileInformation(filePath) returns Stream<String> 

after reading lines in a file.

I would like to replace the getPerson method with a getMale or getFemale method based on the value of an enum

public enum gender {
male,female
}

How can this be achieved used lambda expressions?

Upvotes: 2

Views: 2458

Answers (1)

Roland
Roland

Reputation: 23252

If you just want to filter by gender (assuming there is an accessor like Person.getGender), then you only need to add a filter:

List<Person> malePeople;
malePeople = personDao.getFileInformation(filePath)
                      .skip(1)
                      .map(this::getPerson)
                      .filter(Objects::nonNull)
                      .filter(p -> p.getGender() == gender.male) // or gender.female
                      .collect(Collectors.toList());

If you rather want to group your results, the following will help you:

Map<gender, List<Person>> peopleByGender;
peopleByGender = personDao.getFileInformation(filePath)
                          .skip(1)
                          .map(this::getPerson)
                          .filter(Objects::nonNull)
                          .collect(Collectors.groupingBy(Person::getGender));

now access all your female people with:

List<Person> femalePeople = peopleByGender.get(gender.female);

and the male ones with:

List<Person> malePeople = peopleByGender.get(gender.male);

If you just wanted to use a method to simplify the filter-predicate (p -> p.getGender() == gender.male), then you could use one of the following:

.filter(this::getMale) // or: YourClass::getMale for a static method

where this::getMale refers to the following method:

boolean getMale(Person p) {
   return p.getGender() == gender.male;
}

or

.filter(getMale())

where getMale() refers to the following method:

Predicate<Person> getMale() {
  return p -> p.getGender() == gender.male;
}

Upvotes: 3

Related Questions