Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)

I've just started playing with Java 8 lambdas and I'm trying to implement some of the things that I'm used to in functional languages.

For example, most functional languages have some kind of find function that operates on sequences, or lists that returns the first element, for which the predicate is true. The only way I can see to achieve this in Java 8 is:

lst.stream()

    .filter(x -> x > 5)

    .findFirst()

However, this seems inefficient to me, as the filter will scan the whole list, at least to my understanding (which could be wrong). Is there a better way?

1 Answer

0 votes
by (46k points)

No, the filter doesn't browse the whole stream. It's a standard operation, which passes a lazy stream (truly all standard operations pass a lazy stream). To persuade you, you can easily do the following test:

List<Integer> list = Arrays.asList(1, 10, 3, 7, 5);

int a = list.stream()

            .peek(num -> System.out.println("will filter " + num))

            .filter(x -> x > 5)

            .findFirst()

            .get();

System.out.println(a);

Which outputs:

will filter 1

will filter 10

10

You observe that only the first two elements of the stream are concocted.

So you can go with your procedure which is accurate.

Related questions

Browse Categories

...