Return 元素基于 Stream 中的匹配条件

Return Element based on matching criteria from Stream

我有一个自定义对象 AllData 的列表。我想要 return 此列表中符合特定条件的一个元素 (widgetId = 58)。我将如何使用 stream/filter/collections 到 return 符合我的条件的单个 AllData 对象。我已经尝试了下面的方法,但是我得到了 NoSuchElementException.

AppDatabase db = AppDatabase.getDbInstance(MyContext.getContext());
List<AllData> allDataList = db.allDataDao().getAllDataList();
AllData allData = allDataList.stream().findFirst().filter(e -> e.getMyTicker().getWidgetId() == 58).get();

你应该先 filter 列表然后使用 findFirst

AllData allData = allDataList.stream()
       .filter(e -> e.getMyTicker().getWidgetId() == 58)
       .findFirst().get();

我建议使用 orElse 来避免 NoSuchElementException - 如果 Optional

中没有值

如果什么都没有返回怎么办?您可能希望返回一个默认值并在 filter() 之后调用 findFirst()。给你:

    public static void main(String[] args) {
    List<MyObject> list = new ArrayList<>();
    MyObject object = list.stream().filter(e -> e.getMyTicker().getWidgetId() == 58).findFirst().orElse(null);
}

public static class MyObject {
    private Ticker myTicker;

    public Ticker getMyTicker() {
        return myTicker;
    }
}

public static class Ticker {
    private int widgetId;

    public int getWidgetId() {
        return this.widgetId;
    }
}