Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Stream to find element in list

I have the following class:

public class Item {
    int id;
    String name;
    // few other fields, contructor, getters and setters
}

I have a list of Items. I want to iterate through the list and find the instance which has a particular id. I'm trying to do it through streams.

public void foobar() {

    List<Item> items = getItemList();
    List<Integer> ids = getIdsToLookup();
    int id, i = ids.size() - 1;

    while (i >= 0) {
        id = ids.get(i);
        Optional<Item> item = items
            .stream()
            .filter(a -> a.getId() == id)
            .findFirst();
        // do stuff
        i--;
    }
}

Is this the best way to iterate over the list and get the element I need? Also, I get an error on the filter line for id which says variables used in lambda expressions must be final or effectively final. Maybe I can define id inside the while loop, that should get rid of the exception. Thanks.

like image 759
Gengis Khan Avatar asked Mar 10 '16 22:03

Gengis Khan


People also ask

How do you filter a list of objects using a stream?

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.

How do you check if an element is in a list Java?

ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

What's the difference between findFirst () and findAny ()?

The findAny() method returns any element from a Stream, while the findFirst() method returns the first element in a Stream.


1 Answers

You can try use something like this:

ids.forEach(id -> 
    list.stream()
    .filter(p -> p.getId() == id)
    .findFirst()
    .ifPresent(p -> {
        // do stuff here
    });
);

Optional here shows that your filter method can return a empty stream, so if you call findFirst it can find one or zero elements.

like image 131
ByeBye Avatar answered Nov 08 '22 07:11

ByeBye