1

I have the following method:

public boolean isMsgOk(String msg) {...}

I want to call this method here:

public String[] returnOkMessages(String... msgs) {
    return Arrays
        .asList(messagessgs)
        .stream(message->isMsgOk(message))
        .anyMatch() ???;
}

I want to return a List of Strings for which the isMsgOk method returns true.
How can I collect them?

Eran
  • 387,369
  • 54
  • 702
  • 768
Twi
  • 765
  • 3
  • 13
  • 29

2 Answers2

4

Use filter and then collect to a List:

return Arrays.asList(messagessgs)
             .stream()
             .filter(message->isMsgOk(message))
             .collect(Collectors.toList())

or:

return Arrays.stream(messagessgs)
             .filter(this::isMsgOk)
             .collect(Collectors.toList())

EDIT:

If the output should be an array, use:

return Arrays.stream(messagessgs)
             .filter(this::isMsgOk)
             .toArray(String[]::new)
Eran
  • 387,369
  • 54
  • 702
  • 768
4

Collect them to a List (you could also use a method reference instead of a lambda)

 .filter(this::isMsgOk)
 .toArray(String[]::new);
Eugene
  • 117,005
  • 15
  • 201
  • 306