初始数据
List<Animal> AnimalList = Lists.newArrayList(new Animal("dog", 6), new Animal("dog", 6), new Animal("cat", 7), new Animal("cat", 7), new Animal("cat", 7), new Animal("pig",8));
1)计数
Map<String, Long> map = AnimalList.stream(). collect(Collectors.groupingBy(Animal::getName,Collectors.counting()));
输出结果:{cat=3, dog=2, pig=1}
2) 排序(逆序)
map.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()) .forEachOrdered(System.out::println);
3) 累加求和
Map<String, Integer> sumMap = AnimalList.stream().collect. (Collectors.groupingBy(Animal::getName, Collectors.summingInt(Animal::getPrice)));
输出结果是:{cat=21, dog=12, pig=8}
4) 分组:
Map<String, List<Integer>> groupMap = AnimalList.stream().collect(Collectors.groupingBy(Animal::getName, Collectors.mapping(Animal::getPrice, Collectors.toList())));