Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream - Why is filter method not executing? [duplicate]

I am learning filtering using java stream. But the stream after filtering is not printing anything. I think the filter method is not getting executed. My filtering code is as follows:

Stream.of("d2", "a2", "b1", "b3", "c")
    .filter(s -> {
        s.startsWith("b");
        System.out.println("filter: " + s);
        return true;
    });

There is no compilation error and no exception also. Any suggestion?

like image 614
KayV Avatar asked Nov 29 '16 10:11

KayV


People also ask

Can we have multiple filter in stream Java?

1. Overview. In this tutorial, We'll learn how to utilise stream filter() with several filter conditions (can be more than one condition). Normally, we apply a single condition to streams using filter() method with lambda and then store the results in Lists or Sets.

What is the purpose of filter method of stream in Java 8?

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.

What is the function used to duplicate a stream?

CopyTo(Stream) Reads the bytes from the current stream and writes them to another stream. Both streams positions are advanced by the number of bytes copied.

Can Java 8 have 2 filters?

Combining two filter instances creates more objects and hence more delegating code but this can change if you use method references rather than lambda expressions, e.g. replace filter(x -> x. isCool()) by filter(ItemType::isCool) .


1 Answers

filter is an intermediate operation, which will be executed only if the Stream pipeline ends in a terminal operation.

For example :

Stream.of("d2", "a2", "b1", "b3", "c")
  .filter(s -> {
        s.startsWith("b");
        System.out.println("filter: " + s);
        return true;
  })
  .forEach (System.out::println);

As it is, your filter method is useless, since it always returns true, and thus performs no filtering.

like image 61
Eran Avatar answered Sep 24 '22 09:09

Eran