Java 8 Stream to find element in list

前端 未结 4 682
独厮守ぢ
独厮守ぢ 2021-02-14 02:07

I have the following class:

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

I have

4条回答
  •  猫巷女王i
    2021-02-14 03:06

    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.

提交回复
热议问题