【问题标题】:Return Element based on matching criteria from Stream根据来自 Stream 的匹配条件返回元素
【发布时间】:2021-10-03 16:40:25
【问题描述】:

我有一个自定义对象 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();

【问题讨论】:

  • 您正在调用findFirst(),它将删除除第一个元素之外的所有元素。这是你想要的吗? getWidgetId() 的数据类型是什么?你怎么知道 id 58 存在?
  • 谢谢,死侍提供的答案正是我想要的。

标签: java filter collections java-stream


【解决方案1】:

如果什么都没有返回会发生什么?您可能希望使用默认值并在 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;
    }
}

【讨论】:

    【解决方案2】:

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

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

    我建议使用orElse 来避免 NoSuchElementException - 如果 Optional 中没有值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2019-04-12
      • 2020-09-28
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多