Java 8 Stream to find element in list

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

    If you want to stick with streams and iterate backwards, you could do it this way:

    IntStream.iterate(ids.size() - 1, i -> i - 1)
        .limit(ids.size())
        .map(ids::get) // or .map(i -> ids.get(i))
        .forEach(id -> items.stream()
            .filter(item -> item.getId() == id)
            .findFirst().ifPresent(item -> {
                // do stuff
            }));
    

    This code does the same as yours.

    It iterates backwards, starting with a seed: ids.size() - 1. The initial stream of ints is limited in its size with limit(), so that there are no negative ints and the stream has the same size as the list of ids. Then, a map() operation converts the index to the actual id that is at the ith position at the ids list (this is done by means of invoking ids.get(i)). Finally, the item is searched in the items list the same way as in your code.

提交回复
热议问题