Java 8 Stream to find element in list

前端 未结 4 652
独厮守ぢ
独厮守ぢ 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条回答
  •  隐瞒了意图╮
    2021-02-14 03:02

    You want to find at most one item for each given id and do something with the found item, right? A bit more performance improvement:

    Set idsToLookup = new HashSet<>(getIdsToLookup()); // replace list with Set
    
    items.stream()
        .filter(e -> idsToLookup.remove(e.getId()))
        .forEach(
           /* doing something */
         );
    

提交回复
热议问题