Search code examples
javajava-stream

Filter a Java stream matching either of two criteria


I have an array of words.

I want to get all words that are:

  1. more that 5 chars long and
  2. all words starting with "a" regardless of length

How do I achieve the second criteria?

List<String> words = Arrays.asList("art", "again", "orphanage", "forest", "cat", "bat");
List<String> result = words.stream()
        .filter(word -> word.length() > 5)
        .collect(Collectors.toList());

result.forEach(word -> System.out.println(word));

My expected output should be art again orphanage forest


Solution

  • Predicate<String> isStartWithA = word -> word.startsWith("a");
    Predicate<String> fiveChar = word -> word.length() > 5;
    List<String> words=Arrays.asList("art", "again", "orphanage", "forest", "cat", "bat");
    List<String> result = words.stream() .filter(isStartWithA.or(fiveChar)) 
    .collect(Collectors.toList());
    result.forEach(word -> System.out.println(word))