简体   繁体   中英

Java 8 Stream filtering value of list in a list

I have a an object which looks like the following

class MyObject {

    String type;
    List<String> subTypes;

}

You can do:

myObjects.stream()
         .filter(t -> t.getType().equals(someotherType) && 
                      t.getSubTypes().stream().anyMatch(<predicate>))
         .collect(Collectors.toList());

This will fetch all the MyObject objects which

  • meet a criteria regarding the type member.
  • contain objects in the nested List<String> that meet some other criteria, represented with <predicate>

I saw the accepted answer from @kocko which is both a good answer and totally correct. However there is a slightly alternative approach where you simply chain the filters.

final List<MyObject> withBZ = myObjects.stream()
        .filter(myObj -> myObj.getType().equals("B"))
        .filter(myObj -> myObj.getSubTypes().stream().anyMatch("Z"::equals))
        .collect(Collectors.toList());

This is basically doing the same thing but the && operand is removed in favour of another filter. Chaining works really well for the Java 8 Stream API:s and IMO it is easier to read and follow the code.

I found a bunch of examples at this site: https://zetcode.com/java/streamfilter/

Quoting the example for Java Stream multiple filter operations

It is possible to apply multiple filter operations on a stream.

package com.zetcode;

import java.util.Arrays;
import java.util.function.IntConsumer;

public class JavaStreamMultipleFilters {

public static void main(String[] args) {

    int[] inums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };
    
    IntConsumer icons = i -> System.out.print(i + " ");
    
    Arrays.stream(inums).filter(e -> e < 6 || e > 10)
            .filter(e -> e % 2 == 0).forEach(icons);
}

}

In the example, we apply multiple filter operations on a stream of integers.

int[] inums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };

We have an array of integer values.

IntConsumer icons = i -> System.out.print(i + " ");

IntConsumer is an operation that accepts a single integer value argument and returns no result.

Arrays.stream(inums).filter(e -> e < 6 || e > 10)
        .filter(e -> e % 2 == 0).forEach(icons);

A stream is created from the array with the Arrays.stream method. Multiple filtering operations are performed.

2 4 12 14

These integers fulfill all the filtering conditions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM