Skip to content
Advertisement

java lambda allmatch print value if not match

Having a list of strings, if a string not start with a prefix, I would like to print it. The result will be a boolean, if all strings start with the prefix.

Is there a way to do it in one row?

What is the correct syntax to combined this too :

 return words.stream()
        .allMatch(work -> word.startWith("ab"));

 words.stream()
        .forEach(word -> {
          if (!word.startWith("ab")) {
            System.out.print(word);
          }
        });

Thanks,

Advertisement

Answer

Use Stream.peek to place an operation in the middle of the stream

static boolean testPrefix(List<String> words, String prefix) {
    return words.stream()
            .peek(word -> {
                if (!word.startsWith("ab")) System.out.println(word);
            })
            .allMatch(word -> word.startsWith(prefix));
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement