修改Java Stream逻辑过滤Ingredients为null的Hotdog对象
问题背景
现有Java类定义如下:
public class FastFood { ArrayList<Hotdog> hotdogs; boolean isTasty; } public class Hotdog { String name; Ingredients ingredients; }
已知某FastFood实例的hotdogs集合共存储10个Hotdog对象,其中9个对象的所有属性均完成赋值,剩余1个对象的ingredients属性为null。需要改造现有convert方法,使方法最终仅返回ingredients属性非空的Hotdog集合(预期返回9条有效数据),原方法实现代码如下:
public List<Hotdog> convert(Fastfood fastfood) { List<Hotdog> hotdogs = fastfood.getHotdogs().stream() .map(this::convertToHotdog) .collect(Collectors.toList());
改造方案
直接在Stream流的map操作后增加过滤逻辑,筛掉ingredients为null的对象即可,修改后完整代码如下:
public List<Hotdog> convert(Fastfood fastfood) { List<Hotdog> hotdogs = fastfood.getHotdogs().stream() .map(this::convertToHotdog) // 过滤掉配料属性为空的热狗对象 .filter(hotdog -> hotdog.getIngredients() != null) .collect(Collectors.toList()); return hotdogs; }
补充提示:如果自定义的convertToHotdog方法本身存在返回null的可能,可以在配料非空判断前先加一层对象非空校验,避免触发空指针异常:
// 先过滤掉转换后为null的对象 .filter(Objects::nonNull) // 再过滤配料为null的对象 .filter(hotdog -> hotdog.getIngredients() != null)
使用前记得导入java.util.Objects包。
内容的提问来源于stack exchange,提问作者fat_pikachu
相关产品推荐
相关产品推荐

