常用 Lambda表达式
1、遍历
final List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu", "lishan");
list.forEach(System.out::println);;
2、排序
final List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu", "lishan");
// 第一种
// list.sort(String::compareTo);
// 第二种
// Collections.sort(list, String::compareTo);
// 第三种
Collections.sort(list, (o1, o2) -> o1.compareTo(o2));
list.forEach(System.err::println);
3、过滤
final List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu", "lishan");
List<String> list1 = list.stream().filter(s -> s.startsWith("l")).collect(toList());
list1.forEach(System.out::println);
4、映射
final List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu", "lishan");
List<Integer> collect = list.stream().map(String::length).collect(toList());
collect.forEach(System.out::println);
5、归约
List<Integer> list2 = Arrays.asList(1, 2, 3, 5, 6, 7, 8);
// Integer sum = list2.stream().reduce(0, (a, b) -> a + b);
Integer sum = list2.stream().reduce(0, (a, b) -> {
System.out.printf("%d ,%d \n", a, b);
return a + b;
});
System.out.println(sum);
6、分组
final List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu", "lishan");
Map<Integer, List<String>> collect = list.stream().collect(groupingBy(String::length));
collect.forEach((k, v) -> {
System.out.printf("k=%s,v=%s", k, CollUtil.toList(v));
});
标签:Java,Arrays,List,list,System,collect,out,表达式,Lambda
From: https://www.cnblogs.com/wsx2019/p/17441834.html