一、示例说明
通过java.util.stream.Stream的集合groupingBy分组函数,并筛选符合条件的数据。
二、代码示例
package com.xwood.demo.java8;@b@ @b@import cn.hutool.json.JSONUtil;@b@ @b@import java.util.*;@b@import java.util.stream.Collectors;@b@import java.util.stream.Stream;@b@ @b@import static java.util.stream.Collectors.*;@b@ @b@/**@b@ * @author jun.ni@b@ * @version 1.0.0@b@ * @ClassName MapGroupTest.java@b@ * @Description TODO@b@ * @createTime 2023/8/31 13:36@b@ */@b@//https://blog.csdn.net/zth_killer/article/details/128345590@b@ //https://blog.csdn.net/qq_38530648/article/details/114270058@b@ //https://blog.csdn.net/gerald2008/article/details/106589244/@b@public class MapGroupTest {@b@ @b@ public static String toString(List<Map.Entry<String,Long>> aaa){@b@return null;@b@ }@b@ @b@ public static void main(String[] args) {@b@ List<Person> mapList = new ArrayList<Person>();@b@ Person p1=new Person("1a",1);@b@ Person p2=new Person("2a",2);@b@ Person p3=new Person("3a",3);@b@ Person p4=new Person("2a",4);@b@ Person p5=new Person("5a",5);@b@ Person p6=new Person("3a",6);@b@ mapList.add(p1);@b@ mapList.add(p2);@b@ mapList.add(p3);@b@ mapList.add(p4);@b@ mapList.add(p5);@b@ mapList.add(p6);@b@ @b@ @b@ Map<String,Long> checkOneCarVinMap=mapList.stream().collect(groupingBy(Person::getName, counting()));@b@ @b@ System.out.println(checkOneCarVinMap);//输出:{1a=1, 5a=1, 3a=1, 2a=2}@b@ @b@ System.out.println(checkOneCarVinMap.entrySet().stream().filter(r -> r.getValue() > 1).count());//输出:2@b@ @b@ Stream<Map.Entry<String,Long>> bbb=checkOneCarVinMap.entrySet().stream().filter(r -> r.getValue() > 1);@b@ @b@ System.out.println(JSONUtil.toJsonStr(checkOneCarVinMap.entrySet().stream().filter(r -> r.getValue() > 1).collect(Collectors.toList())));//输出:["3a=2","2a=2"]@b@ @b@ System.out.println(checkOneCarVinMap.entrySet().stream().filter(r -> r.getValue() > 1).map(Map.Entry<String,Long>::getKey).collect(joining(","))); //输出:3a,2a@b@// List<Map.Entry<String,Long>> aaa= checkOneCarVinMap.entrySet().stream().filter(r -> r.getValue() > 1).collect(Collectors.toList());@b@//@b@// StringBuffer sb =new StringBuffer("");@b@// aaa.stream().forEach(a->{@b@// sb.append(a.getKey());@b@// });@b@// System.out.println(sb.toString());@b@ @b@ List<String> abc=Arrays.asList(new String[]{"aaa","bbb"});@b@ System.out.println(String.join(",",abc));@b@ @b@ @b@ @b@ }@b@}