toList List<T>
把流中所有元素收集到List中
示例:List<Menu> menus=Menu.getMenus.stream().collect(Collectors.toList())
Joining String
连接流中每个元素的toString方法生成的字符串
示例:String name=Menu.getMenus.stream().map(Menu::getName).collect(joining(“, ”))
maxBy Optional<T>
一个包裹了流中按照给定比较器选出的最大元素的optional
如果为空返回的是Optional.empty()
示例:Optional<Menu> fattest=Menu.getMenus.stream().collect(maxBy(Menu::getCalories))
groupingBy Map<K,List<T>>
根据流中元素的某个值对流中的元素进行分组,并将属性值做为结果map的键
Map<String, List<Person>> resultMap = personList.stream().collect(Collectors.groupingBy(c -> c.getAddress()));
filter 过滤
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
mapreduce 求和
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
Collectors.maxBy 求最大最小值
Optional<Dish> maxDish = Dish.menu.stream().
collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
maxDish.ifPresent(System.out::println);
去重
List<Person> unique = appleList.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
);
distinct去重(List<Color>中的Color对象去重,记得重写hashCode()与equeals()方法。)
List<Color> colors = skusResult.getValue().stream().map(Sku::getColor).distinct().collect(Collectors.toList());
anyMatch 是否存在
boolean match = gaPaymentChangeDetailList.stream().anyMatch(detail -> GaConstants.SUPPLEMENT_BILL.equals(detail.getIsSupplementBill()));
foreach 遍历对象
page.getRows().stream().forEach(x -> x.setOrderTime((DateUtils.dateFormat(x.getCreateTime(),DateUtils.DAT_SHORT_FORMATSS))));
List 对象转换
List<Menu>menus= menuService.queryMenuList(query);List<MenuTreeVO> menuTrees = menus.stream().map(MenuTreeVO::new).collect(Collectors.toList());
把List<Menu>转成了 List<MenuTreeVO>,其中的map(MenuTreeVO::new)等价于map(menu->new MenuTreeVO(menu))
collections排序
//之前的排序我们可以这样写
Collections.sort(list, new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return -o1.compareTo(o2);
}
});
//使用Lambda表达式
Collections.sort(list,(String s1,String s2)->{
return s1.compareTo(s2);
});
//可以简写为
//1.大括号里面就一句代码
//2.编译器可以自动推导出参数类型
Collections.sort(list,(s1,s2)->s1.compareTo(s2));
本文总结了Java8 Lambda表达式的常用语法,包括toList、joining、maxBy、groupingBy、filter、mapReduce、distinct去重、anyMatch、foreach遍历及List对象转换和排序等操作。通过实例展示了Lambda在集合处理中的高效与简洁。
477

被折叠的 条评论
为什么被折叠?



