Stream流解决java问题

Stream流解决java问题,第1张

Stream流解决java问题

文章目录
      • 1.题目①
      • 2.题目②
      • 3.双循环判断值

1.题目①

需求:

筛选出卡路里小于 400 的菜肴
筛选后的进行排序
获取排序后的名字

菜肴.class:

public class Dish {
    private String name;
    private boolean vegetarian;
    private int calories;
    private Type type;
    // getter and setter
}

java 8 之前

private List beforeJava7(List dishList) {
    List lowCaloricDishes = new ArrayList<>();

    //1.筛选出卡路里小于400的菜肴
    for (Dish dish : dishList) {
        if (dish.getCalories() < 400) {
            lowCaloricDishes.add(dish);
        }
    }

    //2.对筛选出的菜肴进行排序
    Collections.sort(lowCaloricDishes, new Comparator() {
        @Override
        public int compare(Dish o1, Dish o2) {
            return Integer.compare(o1.getCalories(), o2.getCalories());
        }
    });

    //3.获取排序后菜肴的名字
    List lowCaloricDishesName = new ArrayList<>();
    for (Dish d : lowCaloricDishes) {
        lowCaloricDishesName.add(d.getName());
    }

    return lowCaloricDishesName;
}

Stream流:

private List afterJava8(List dishList) {
    return dishList.stream()
            .filter(d -> d.getCalories() < 400) //筛选出卡路里小于400的菜肴
            .sorted(comparing(Dish::getCalories)) //根据卡路里进行排序
            .map(Dish::getName) //提取菜肴名称
            .collect(Collectors.toList()); //转换为List
}
2.题目②

数据库查询到的菜肴根据菜肴种类进行分类,返回一个Map

java 8 以前

private static Map> beforeJDK8(List dishList) {
    Map> result = new HashMap<>();

    for (Dish dish : dishList) {
        //不存在则初始化
        if (result.get(dish.getType())==null) {
            List dishes = new ArrayList<>();
            dishes.add(dish);
            result.put(dish.getType(), dishes);
        } else {
            //存在则追加
            result.get(dish.getType()).add(dish);
        }
    }

    return result;
}

Stream流;

private static Map> afterJDK8(List dishList) {
    return dishList.stream().collect(groupingBy(Dish::getType));
}
3.双循环判断值

java 8 以前

List newChilds = new ArrayList();
for(Model model : models){
	String code = model.getCode();
	for(ChildModel childModel : childs){
		if(code.equals(childModel.getCode())){
			newChilds.add(childModel);
		}
	}
}

Stream

List codes = models.stream()
	.map(item -> item.getCode())
	.collect(Collectors.toList());
List newChilds = childs.stream()
	.filter(item -> codes.contains(item.getCode()))
	.collect(Collectors.toList());

Stream filter + anyMatch

List newChilds = childs.stream()
	.filter(child -> models.stream()
		.anyMatch(item -> item.getCode().equals(child.getCode())))
	.collect(Collectors.toList());

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5694365.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存