list对象转map stream /去重( 根据属性转Map或者分组)

list对象转map stream /去重( 根据属性转Map或者分组)_第1张图片

根据某属性转换成Map , List转成Map

由List转成以Student的id当成Key,而Student当成Value的Map操作,即Map形式

List list = new ArrayList<>;
Studnet studnet = new Studnet();
studnet.setId("a1")
studnet.setName("张三");
list.add(studnet);

Studnet studnet2 = new Studnet();
studnet2.setId("a1")
studnet2.setName("张三");
list.add(studnet2);

//避免key一样报错Duplicate key,【Function.identity()= a->a】
Map map = list.stream.collect(Collectors.toMap(Studnet::getId,a->a,(key1,key2)->key2));

for(Map.Entry m: map.entrySet()){
    System.out.printLn("key:"+m.getKey()+"- value:"+m.getValue());
} 

根据某属性分组, List转成Map>

Map> studnetGroup= list.stream.collect(Collectors.groupingBy(Student::getId));

//操作属性值,然后进行分组
Map> studnetGroup= list.stream.collect(Collectors.groupingBy(x->x.getName().substring(0,x.getName().length()-1));

for(Map.Entry> data : studentGroup.entrySet()){
     System.out.printLn("key:"+data.getKey()+"- value:"+data.getValue());
     List studnetList = data.getValue();
     studnetList.stram.foreach(x->System.out.println(x))
}

list对象 按照属性去重

List  studentList =new ArrayList<>;
Student student = new  Student();
        student.setName("zhangsan");
        student.setAge(12);
        strudentList.add(student);
Set  studentSet = new TreeSet<>(Comparator.comparing(s->(s.getName())));
              studnet.addAll(studnetList);
List  resultList=new Array<>(studentList);

你可能感兴趣的:(java,java,开发语言)