我有一个自定义对象AllData的列表。我想从这个列表中返回一个元素,它与一个特定的标准(widgetId = 58)相匹配。如何使用流/筛选器/集合返回与我的条件匹配的单个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();发布于 2021-07-27 21:33:59
您应该首先filter列表和使用findFirst
AllData allData = allDataList.stream()
.filter(e -> e.getMyTicker().getWidgetId() == 58)
.findFirst().get();我建议使用orElse来避免NoSuchElementException --如果在可选中没有值的话。
发布于 2021-07-27 23:54:44
如果什么都不返回会发生什么?您希望返回一个默认值,并在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;
}
}https://stackoverflow.com/questions/68551925
复制相似问题