How to filter a List using Java 8 stream and startwith array of values
You call startsWith
on the wrong String
s (for example, you test if "1_".startsWith("1_John")
instead of "1_John".startsWith("1_")
).
You should stream over nameList
and use numberList
for the filtering:
List<String> filteredList =
nameList.stream()
.filter(str -> numberList.stream().anyMatch(str::startsWith))
.collect(Collectors.toList());
P.S. Stream.of(numberList.toArray(new String[0]))
is redundant. Use numberList.stream()
instead.
As an alternate to Eran's solution, you can also use a combination of removeIf
and noneMatch
as follows:
List<String> filteredList = new ArrayList<>(nameList);
filteredList.removeIf(str -> numberList.stream().noneMatch(str::startsWith));