根据某属性转换成Map , List<Student>转成Map<String, Student>
由List<Student>转成以Student的id当成Key,而Student当成Value的Map操作,即Map<String, Student>形式
List<Student> 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<String,Studnet> map = list.stream.collect(Collectors.toMap(Studnet::getId,a->a,(key1,key2)->key2));
for(Map.Entry<String,Studnet> m: map.entrySet()){
System.out.printLn("key:"+m.getKey()+"- value:"+m.getValue());
}
根据某属性分组, List<Student>转成Map<String, List<Student>>
Map<String,List<Studnet>> studnetGroup= list.stream.collect(Collectors.groupingBy(Student::getId));
//操作属性值,然后进行分组
Map<String,List<Studnet>> studnetGroup= list.stream.collect(Collectors.groupingBy(x->x.getName().substring(0,x.getName().length()-1));
for(Map.Entry<String,List<Studnet>> data : studentGroup.entrySet()){
System.out.printLn("key:"+data.getKey()+"- value:"+data.getValue());
List<Studnet> studnetList = data.getValue();
studnetList.stram.foreach(x->System.out.println(x))
}
list对象 按照属性去重
List<Student> studentList =new ArrayList<>; Student student = new Student(); student.setName("zhangsan"); student.setAge(12); strudentList.add(student); Set<Student> studentSet = new TreeSet<>(Comparator.comparing(s->(s.getName()))); studnet.addAll(studnetList); List<Student> resultList=new Array<>(studentList);