- 求和(Sum)示例代码如下所示:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::valueOf).sum();
1. System.out.println("数字列表的和为:" + sum);
2.分组(Grouping)示例代码如下所示:
List<String> fruits = Arrays.asList("apple", "banana", "orange", "grape");
Map<Character, List<String>> groupedFruits = fruits.stream()
.collect(Collectors.groupingBy(fruit -> fruit.charAt(0)));
System.out.println("按首字母分组后的水果列表:" + groupedFruits);
3.排序
1.正向排
userList.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
2.倒序排
userList.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
主要差别再鱼reversed() 函数