682

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?

Lii
  • 11,553
  • 8
  • 64
  • 88
siki
  • 9,077
  • 3
  • 27
  • 36
  • 75
    It's not inefficient, Java 8 Stream implementation is lazy evaluated, so filter is applied only to terminal operation. Same question here: http://stackoverflow.com/questions/21219667/stream-and-lazy-evaluation – Marek Gregor May 16 '14 at 13:35
  • 1
    Cool. That's what I hoped it'd do. It would've been a major design flop otherwise. – siki May 16 '14 at 13:52
  • 2
    If your intention is really to check whether the list contains such an element at all (not single out the first of possibly several), .findAny() can theoretically be more efficient in a parallell setting, and of course communicates that intent more clearly. – Joachim Lous Apr 20 '16 at 09:01
  • 2
    Compared to a simple forEach cycle, this would create lots of objects on the heap and dozens of dynamic method calls. While this might not always affect the bottom line in your performance tests, in the hot spots it makes a difference to abstain from the trivial use of Stream and similar heavyweight constructs. – Agoston Horvath Sep 22 '16 at 14:07

8 Answers8

911

No, filter does not scan the whole stream. It's an intermediate operation, which returns a lazy stream (actually all intermediate operations return a lazy stream). To convince you, you can simply 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 see that only the two first elements of the stream are actually processed.

So you can go with your approach which is perfectly fine.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • 53
    As a note, I used `get();` here because I know which values I feed to the stream pipeline and hence that there will be a result. In practice, you should not use `get();`, but `orElse()` / `orElseGet()` / `orElseThrow()` (for a more meaningful error instead of a NSEE) as you might not know if the operations applied to the stream pipeline will result in an element. – Alexis C. Feb 24 '16 at 17:22
  • 46
    `.findFirst().orElse(null);` for example – Gondy Nov 11 '16 at 09:12
  • 26
    Don't use orElse null. That should be an anti-pattern. It is all included in the Optional so why should you risk a NPE? I think dealing with Optional is the better way. Just test the Optional with isPresent() before you use it. – BeJay Jan 04 '18 at 09:55
  • @BeJay i don't understand. what should I use instead of `orElse` ? – John Henckel Sep 06 '19 at 14:45
  • 8
    @JohnHenckel I think what BeJay means is that you should leave it as an `Optional` type, which is what `.findFirst` returns. One of the uses of Optional is to help developers avoid having to deal with `null`s. e.g. instead of checking `myObject != null`, you can check `myOptional.isPresent()`, or use other parts of the Optional interface. Did that make it clearer? – Alexander Terp Jan 19 '20 at 22:43
  • For my use case, I want and integer field from an object. I needed to add a `map()` step as: `filter( x -> x.age > 5 ).map( x -> x.height ).first().orElse(0)`. – will Mar 17 '22 at 05:05
  • Then what's the purpose of the *findFirst()* method here? – Vengadesh KS Mar 16 '23 at 08:04
126

However this seems inefficient to me, as the filter will scan the whole list

No it won't - it will "break" as soon as the first element satisfying the predicate is found. You can read more about laziness in the stream package javadoc, in particular (emphasis mine):

Many stream operations, such as filtering, mapping, or duplicate removal, can be implemented lazily, exposing opportunities for optimization. For example, "find the first String with three consecutive vowels" need not examine all the input strings. Stream operations are divided into intermediate (Stream-producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy.

wha'eve'
  • 3,490
  • 2
  • 11
  • 6
  • 8
    This answer was more informative to me, and explains the why, not only how. I never new intermediate operations are always lazy; Java streams continue to surprise me. – kevinarpe Jul 06 '15 at 07:45
62
return dataSource.getParkingLots()
                 .stream()
                 .filter(parkingLot -> Objects.equals(parkingLot.getId(), id))
                 .findFirst()
                 .orElse(null);

I had to filter out only one object from a list of objects. So i used this, hope it helps.

RubioRic
  • 2,442
  • 4
  • 28
  • 35
CodeShadow
  • 3,503
  • 1
  • 17
  • 16
  • BETTER: since we looking for a boolean return value, we can do it better by adding null check: return dataSource.getParkingLots().stream().filter(parkingLot -> Objects.equals(parkingLot.getId(), id)).findFirst().orElse(null) != null; – shreedhar bhat Apr 03 '19 at 09:48
  • 3
    @shreedharbhat You should not need to do `.orElse(null) != null`. Instead, make use of the Optional API's `.isPresent` i.e. `.findFirst().isPresent()`. – Alexander Terp Jan 19 '20 at 22:47
  • 1
    @shreedharbhat first of all OP was not looking for a boolean return value. Second of all if they were, it would be been cleaner to write `.stream().map(ParkingLot::getId).anyMatch(Predicate.isEqual(id))` – Ozymandias May 17 '20 at 05:08
  • This one is good and works well. You can get a whole object within a list however, I would like to make a corrections. You wrote `equals` but it is `equal` so as follows: `.filter(parkingLot -> Objects.equal(parkingLot.getId(), id))` – Vibran Dec 29 '21 at 11:01
  • flawless answer! – Gaurav Jan 31 '22 at 13:10
22

In addition to Alexis C's answer, If you are working with an array list, in which you are not sure whether the element you are searching for exists, use this.

Integer a = list.stream()
                .peek(num -> System.out.println("will filter " + num))
                .filter(x -> x > 5)
                .findFirst()
                .orElse(null);

Then you could simply check whether a is null.

RubioRic
  • 2,442
  • 4
  • 28
  • 35
Ifesinachi Bryan
  • 2,240
  • 1
  • 19
  • 20
  • 2
    You should fix your example. You can not assign null to a plain int. https://stackoverflow.com/questions/2254435/can-an-int-be-null-in-java – RubioRic Feb 05 '18 at 16:53
  • I've edited your post. 0 (zero) may be a valid result when you are searching in a list of integers. Replaced variable type by Integer and default value by null. – RubioRic Feb 07 '18 at 12:17
  • flawless answer! – Gaurav Jan 31 '22 at 13:11
16

Already answered by @AjaxLeung, but in comments and hard to find.
For check only

lst.stream()
    .filter(x -> x > 5)
    .findFirst()
    .isPresent()

is simplified to

lst.stream()
    .anyMatch(x -> x > 5)
Grigory Kislin
  • 16,647
  • 10
  • 125
  • 197
4

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

// Stream is ~30 times slower for same operation...
public class StreamPerfTest {

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


    // 55 ms
    @Test
    public void stream() {

        for (int i = 0; i < iterations; i++) {
            Optional<Integer> result = list.stream()
                    .filter(x -> x > 5)
                    .findFirst();

            System.out.println(result.orElse(null));
        }
    }

    // 2 ms
    @Test
    public void loop() {

        for (int i = 0; i < iterations; i++) {
            Integer result = null;
            for (Integer walk : list) {
                if (walk > 5) {
                    result = walk;
                    break;
                }
            }
            System.out.println(result);
        }
    }
}

aillusions
  • 194
  • 1
  • 15
  • That's the reason I refrain from using streams for simple tasks. It is usually wayyy slower than using simple iteration. (It is even worse if you use array operations. But who does that, anyways... ) – Vankog Oct 27 '21 at 08:57
2

A generic utility function with looping seems a lot cleaner to me:

static public <T> T find(List<T> elements, Predicate<T> p) {
    for (T item : elements) if (p.test(item)) return item;
    return null;
}

static public <T> T find(T[] elements, Predicate<T> p) {
    for (T item : elements) if (p.test(item)) return item;
    return null;
}

In use:

List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
Integer[] intArr = new Integer[]{1, 2, 3, 4, 5};

System.out.println(find(intList, i -> i % 2 == 0)); // 2
System.out.println(find(intArr, i -> i % 2 != 0)); // 1
System.out.println(find(intList, i -> i > 5)); // null
lawrence-witt
  • 8,094
  • 3
  • 13
  • 32
0

Improved One-Liner answer: If you are looking for a boolean return value, we can do it better by adding isPresent:

return dataSource.getParkingLots().stream().filter(parkingLot -> Objects.equals(parkingLot.getId(), id)).findFirst().isPresent();
shreedhar bhat
  • 4,779
  • 1
  • 18
  • 23