Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Streams - Filter More Than One Condition

Based on some sports results data, I have a Fixture object which has getHome() and getAway() method. I'd like to shorten this method which I've written to only use a single lambda function (instead of creating a new list and two lambdas), is this possible?

    private Collection<FixtureResult> finalResults(Team team) {

    List<FixtureResult>finalResults = new ArrayList<>();

    List<FixtureResult> homeResults = resultList.stream().filter(fixture ->
            fixture.getHome().equals(team))
            .collect(toList());

    List<FixtureResult> awayResults = resultList.stream().filter(fixture ->
            fixture.getAway().equals(team))
            .collect(toList());

    finalResults.addAll(homeResults);
    finalResults.addAll(awayResults);

    return finalResults;
}
like image 847
Clatty Cake Avatar asked Mar 19 '18 16:03

Clatty Cake


People also ask

Can we have multiple filter in stream Java?

The Stream API allows chaining multiple filters. We can leverage this to satisfy the complex filtering criteria described. Besides, we can use the not Predicate if we want to negate conditions.

Can Java 8 have 2 filters?

More filters can be applied in a variety of methods, such using the filter() method twice or supplying another predicate to the Predicate.

Is Java stream filter faster than for loop?

If you have a small list, loops perform better. If you have a huge list, a parallel stream will perform better. Purely thinking in terms of performance, you shouldn't use a for-each loop with an ArrayList, as it creates an extra Iterator instance that you don't need (for LinkedList it's a different matter).


1 Answers

Simple enough

resultList.stream()
        .filter(fixture -> fixture.getHome().equals(team) || fixture.getAway().equals(team)))
        .collect(toList());

EDIT: This is on the assumption that order does not matter to you. If your final list needs to have home result and then away, have a look at Elliott Frisch's answer.

like image 178
user7 Avatar answered Oct 01 '22 19:10

user7