taranaki
taranaki

Reputation: 808

Java 8 Stream API how to reuse custom method

I have a method like:

private List<Person> findFilteredPersons(List<Person> persons,
            Predicate<Person> filter) {
        return persons
                .stream()
                .filter(filter)
                .sorted(BY_NAME.thenComparing(BY_AGE))
                .collect(Collectors.toList());
}

Now I would like to use this method in several places, but in one place I don't need to filter the list, I just want to sort it. What is the best way to achieve this?

Upvotes: 2

Views: 534

Answers (2)

Holger
Holger

Reputation: 298123

It’s unlikely that you will run into performance issue when simply using a x -> true predicate to indicate “no filtering”, however, if you want to express the unfiltered operation as such for clarity, the solution is straight-forward: as always for such kind of code organization, split the operation into the distinct parts and the common part:

private List<Person> findFilteredPersons(List<Person> persons, Predicate<Person> filter) {
    return collectSortedPersons(persons.stream().filter(filter));
}
private List<Person> findPersons(List<Person> persons) {
    return collectSortedPersons(persons.stream());
}
private List<Person> collectSortedPersons(Stream<Person> persons) {
    return persons
            .sorted(BY_NAME.thenComparing(BY_AGE))
            .collect(Collectors.toList());
}

Upvotes: 5

Reut Sharabani
Reut Sharabani

Reputation: 31339

To take all items (practically ignoring the filter), pass a predicate that takes all people:

p -> true

You can create another method:

private List<Person> findPeople(List<Person> persons) {
    return findFilteredPersons(persons, p -> true);
}

Upvotes: 5

Related Questions