Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream API filter

I have code:

static void doSmth() {
    ArrayList<String> list = new ArrayList<>();
    for (int i = 0; i < 30; i++) {
        list.add(String.valueOf(i));
    }
    list.stream().filter("1329"::contains).map(s -> s + "a").forEach(System.out::println);
}

Why i got:

 1a
 2a
 3a
 9a
 13a
 29a

I expected a empty output, because list doesn't contains "1329".

like image 928
harp1814 Avatar asked Jun 20 '19 17:06

harp1814


People also ask

What is filter in stream API?

Stream filter(Predicate predicate) returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation.

How does stream filter work Java?

Stream. filter() is a method in Java we use while working with streams. It traverses through all the elements present and removes or filters out all those elements that are not matching with the specified condition through a significant argument.

What is filter () in Java?

A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. Filters perform filtering in the doFilter method.

How do I filter a list based on another list in Java 8?

After populating both the lists, we simply pass a Stream of Employee objects to the Stream of Department objects. Next, to filter records based on our two conditions, we're using the anyMatch predicate, inside which we have combined all the given conditions. Finally, we collect the result into filteredList.


1 Answers

because

.filter("1329"::contains)

mean

.filter(s -> "1329".contains(s))

not

.filter(s -> s.contains("1329"))

As I guess you think it means.

So your list hold :

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ... 25, 26, 27, 28, 29]
    ^  ^  ^                 ^               ^                           ^

Which "1329" contains 1,2, 3, 9, 13 and 29

like image 144
YCF_L Avatar answered Sep 23 '22 08:09

YCF_L