Java Stream API filter

Viewed 1460

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".

3 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

That's because when you are iterating from 0 to 29, the .contains just checks if each individual element in the list is present or not in the string 1329.

Since 1,2,3... are present they return true, hence they get mapped and appended with "a". If you want to check whether the entire string 1329 is present then use the .equals()

filter("1329"::equals)

You are getting the above output because you are using "1329" Java String to check whether it contains any of the Strings from the list. Since String "1329" contains ["1", "2", "3", "9", "13", "29"], so it filters them out and then you are appending "a" to each filtered string.

In order to check whether the list contains "1329", you can directly use contains() method on java.utit.List. It should fetch the empty set since the list doesn't contain "1329" String.

In order to fetch the Strings from the list which are equal to "1329", you can use the filter method along with String equals method.

list
    .stream()
    .filter(s -> "1329".equals(s))
    .map(s -> s + "a")
    .forEach(System.out::println);

Now, in your case the above code will give nothing in output since the list doesn't contain "1329" String.

Related