lambda表达式对集合的一些操作,持续记录一下新的用法
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(3);
list.add(2);
list.forEach(integer -> {
// 更多的是做一些事情,如果只做一个输出操作,可以用list.forEach(System.out::println);
System.out.println(integer);
});
// 临时改变并操作
list.stream().map(i -> i * 3).forEach(System.out::println);// 输出为计算后的值
// 并不改变原有对象
list.forEach(i -> i = i * 3);
list.forEach(System.out::println);// 输出为原来集合里边的值
// 过滤操作
List<String> strList = Arrays.asList("abc", "eqwr", "bcd", "qb", "ehdc", "jk");
List<String> filtered = strList.stream().filter(x -> x.length() > 2).collect(Collectors.toList());
System.out.printf("Original List : %s, filtered list : %s %n", strList, filtered);
// 改变集合里边每个元素,返回类型可String可list
List<String> strList1 = Arrays.asList("abc", "eqwr", "bcd", "qb", "ehdc", "jk");
String collect = strList1.stream().map(String::toUpperCase).collect(Collectors.joining(","));
List<String> strList2 = strList1.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.printf("filtered collect : %s, strList2 : %s %n", collect, strList2);
//获取数字的个数、最小值、最大值、总和以及平均值
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream().mapToInt(x -> x).summaryStatistics();
System.out.println("Highest prime number in List : " + stats.getMax());
System.out.println("Lowest prime number in List : " + stats.getMin());
System.out.println("Sum of all prime numbers : " + stats.getSum());
System.out.println("Average of all prime numbers : " + stats.getAverage());
// 分组
Map<Integer, List<DockingDealInfoBo>> collect = listToExcel.stream().collect(Collectors.groupingBy(DockingDealInfoBo::getDockingType));