【问题标题】:Filter Java stream if specific object is a null如果特定对象为空,则过滤 Java 流
【发布时间】:2022-06-10 21:31:31
【问题描述】:

我有对象 FastFood。在 ArrayList 中有 10 条热狗。

public class FastFood {
    ArrayList<Hotdog> hotdogs;
    boolean isTasty;
}

public class Hotdog {
    String name;
    Ingredients ingredients;
}

对于 9 条热狗,所有数据都已填满。 对于 1 个热狗,对象成分为空。

我怎样才能修改下面的方法以只包含这些热狗,这些热狗已经填充了成分? (我想看 9 条热狗)。

public List<Hotdog> convert(Fastfood fastfood) {
      List<Hotdog> hotdogs = fastfood.getHotdogs().stream()
                    .map(this::convertToHotdog)
                    .collect(Collectors.toList());

【问题讨论】:

    标签: java stream


    【解决方案1】:

    使用filter()方法,像这样

    List<Hotdog> hotdogs = fastfood.getHotdogs().stream()
                        .map(this::convertToHotdog)
                        .filter(hotdog->hotdog.getIngredients()!=null)
                        .collect(Collectors.toList());
    

    注意:我假设您在 Hotdog 类中的成分字段中有 getter 方法,称为 getIngredients()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-20
      • 2015-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多