Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a List using Java 8 stream and startwith array of values

I have 2 Lists, the one contains a list of numbers and the other a list of names. I have prefixed the names with a number from the first list, followed by an underscore. I want to filter the second list based on all the numbers found in the first list.

What I have tried.

List<String> numberList = new ArrayList<>();
numberList.add("1_");
numberList.add("9_");

List<String> nameList = new ArrayList<>();
nameList.add("1_John");
nameList.add("2_Peter");
nameList.add("9_Susan");

List<String> filteredList = Stream.of(numberList.toArray(new String[0]))
                .filter(str -> nameList.stream().anyMatch(str::startsWith))
                .collect(Collectors.toList());

The code above runs with no error, but the filteredList is empty. Clearly I am doing something wrong.

The filteredList should contain only:

1_John

9_Susan

like image 777
Quentinb Avatar asked May 28 '19 06:05

Quentinb


People also ask

Which methods can you use to filter and slice a stream in Java 8 +?

Streams Filtering & Slicing Basics: Java 8 Streams support declarative filtering out of elements along with the ability to slice-off portions of a list. Streams support four operations to achieve this – filter() , distinct() , limit(n) and skip(n) .

How does filter work in Java Stream?

The filter() function of the Java stream allows you to narrow down the stream's items based on a criterion. If you only want items that are even on your list, you can use the filter method to do this. This method accepts a predicate as an input and returns a list of elements that are the results of that predicate.


2 Answers

You call startsWith on the wrong Strings (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.

like image 122
Eran Avatar answered Oct 26 '22 16:10

Eran


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));
like image 35
Naman Avatar answered Oct 26 '22 17:10

Naman