- 1.题目①
- 2.题目②
- 3.双循环判断值
需求:
筛选出卡路里小于 400 的菜肴
对筛选后的进行排序
获取排序后的名字
菜肴.class:
public class Dish { private String name; private boolean vegetarian; private int calories; private Type type; // getter and setter }
java 8 之前
private ListbeforeJava7(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 List2.题目②afterJava8(List dishList) { return dishList.stream() .filter(d -> d.getCalories() < 400) //筛选出卡路里小于400的菜肴 .sorted(comparing(Dish::getCalories)) //根据卡路里进行排序 .map(Dish::getName) //提取菜肴名称 .collect(Collectors.toList()); //转换为List }
数据库查询到的菜肴根据菜肴种类进行分类,返回一个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 Map3.双循环判断值> afterJDK8(List dishList) { return dishList.stream().collect(groupingBy(Dish::getType)); }
java 8 以前
ListnewChilds = new ArrayList(); for(Model model : models){ String code = model.getCode(); for(ChildModel childModel : childs){ if(code.equals(childModel.getCode())){ newChilds.add(childModel); } } }
Stream
Listcodes = 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
ListnewChilds = childs.stream() .filter(child -> models.stream() .anyMatch(item -> item.getCode().equals(child.getCode()))) .collect(Collectors.toList());
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)