一、Stream流的使用
1.1、分组
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
1.2、List转Map
/** * List -> Map * 需要注意的是: * toMap 如果集合对象有重复的key,会报错Duplicate key .... * apple1,apple12的id都为1。 * 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2 */ Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
1.3、过滤Filter : 从集合中过滤出来符合条件的元素
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
1.4、求和
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
1.5、最大值 最小值
Dish maxDish = Dish.menu.stream().collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories))).get();//获取最大值的对象 Dish minDish = Dish.menu.stream().collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories))).get(); //获取最小值的对象
1.6、去重
List<Person> unique = appleList.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new));
1.7、并行流:parallelStream 排序会乱序
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); numbers.parallelStream().forEach(num->System.out.println(num)); 输出:3 4 2 6 7 9 8 1 5