分组

  1. Map<Integer, List<Apple>> groupBy = appleList.stream()
  2. .collect(Collectors.groupingBy(Apple::getId));
  1. Map<Boolean, List<Person>> part = personList.stream()
  2. .collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));

List 转 Map

  1. Map<Integer, Apple> appleMap = appleList.stream()
  2. .collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));

过滤

  1. List<Apple> filterList = appleList.stream()
  2. .filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());

求和

  1. BigDecimal totalMoney = appleList.stream()
  2. .map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

最大值

  1. Optional<Dish> maxDish = Dish.menu.stream().
  2. collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
  3. maxDish.ifPresent(System.out::println);

最小值

  1. Optional<Dish> minDish = Dish.menu.stream().
  2. collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));
  3. minDish.ifPresent(System.out::println);

去重

  1. List<Person> unique = appleList.stream().collect(
  2. collectingAndThen(
  3. toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
  4. );

原文

java8 快速实现List转map 、分组、过滤等操作