对象属性为数组,根据属性分组统计
数据结构:
[
{"id":"1","name":["aa","bb"]},
{"id":"1","name":["bb","cc"]}
]
需求:我们需要将name里面的属性值进行分组统计个数
方法一:
ArrayList<Person> peoples = new ArrayList<>();
peoples.add(new Person("1", Stream.of("aa", "bb").collect(Collectors.toList())));
peoples.add(new Person("2", Stream.of("bb", "cc").collect(Collectors.toList())));
Map<String, Integer> collect = peoples.stream().flatMap(people -> people.getName().stream()).collect(Collectors.toMap(k -> k, v -> 1, Integer::sum));
System.out.println(collect);
方法二:
HashMap<String, Integer> map = new HashMap<>();
ArrayList<Person> peoples = new ArrayList<>();
peoples.add(new Person("1", Stream.of("aa", "bb").collect(Collectors.toList())));
peoples.add(new Person("2", Stream.of("bb", "cc").collect(Collectors.toList())));
peoples.stream().flatMap(people -> people.getName().stream()).forEach(str -> map.merge(str, 1, Integer::sum));
map.forEach((k, v) -> System.out.println(k + " " + v));
一个map,过滤value的值大于3的map
Map<String, List<ChatVo>> sendMap=new HashMap();
我们想过滤value的size大于3的map:
Map<String, List<ChatVo>> sendMap=sendMap.entrySet().stream().filter(a -> a.getValue().size() > 3).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));