Java 8 Stream to find element in list

前端 未结 4 670
独厮守ぢ
独厮守ぢ 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:00

    If you have lots of ids to search, it's recommended to use a solution which does it in a single pass rather than doing a linear search for each id:

    Map> map=ids.stream()
        .collect(Collectors.toMap(id -> id, id -> Optional.empty()));
    items.forEach(item ->
        map.computeIfPresent(item.getId(), (i,o)->o.isPresent()? o: Optional.of(item)));
    for(ListIterator it=ids.listIterator(ids.size()); it.hasPrevious();) {
        map.get(it.previous()).ifPresent(item -> {
            // do stuff
        });
    }
    

    The first statement simply create a map out of the ids list, mapping each search id to an empty Optional.

    The second statement iterates over the items using forEach and for each item, it checks whether there’s a mapping from its id to an empty Optional and will replace it with an Optional encapsulating the item, if there is such a mapping, all in one operation, computeIfPresent.

    The last for loop iterates backwards over the ids list, as you wished to process them in that order and perform the action if there’s a non-empty Optional. Since the map was initialized with all ids found in the list, get will never return null, it will return an empty Optional, if the id was not found in the items list.

    That way, assuming that the Map’s lookup has O(1) time complexity, which is the case in typical implementations, the net time complexity changed from O(m×n) to O(m+n)

提交回复
热议问题