An example of grouping function of java8 stream

preface

Recently, I encountered a problem in project development. According to business requirements, The parameters sent from the front end to the back end are a list (e.g. list), so the back-end also uses a list to receive. However, after the back-end gets the data, I find that I need to uniformly process the data with the same CLassID. Therefore, I go to the front-end sister to discuss and see if she can help package the data with the same CLassID into a list and send it to me. I can modify the receiving parameters to the following format (list):

class Dto{
  String classId;
  List<Student> list;
}

At this time, my sister assessed the degree of change and looked at me tearfully

I understood in an instant. My chance to show!

I said: Well! The front end doesn't move, and the back end handles it!

You can't say no!

After a careful look at the data, it can be easily solved by using the Java 8 stream grouping function.

public static void testStreamGroup(){
  List<Student> stuList = new ArrayList<Student>();
  Student stu1 = new Student("10001","孙权","1000101",16,'男');
  Student stu2 = new Student("10001","曹操","1000102",'男');
  Student stu3 = new Student("10002","刘备","1000201",'男');
  Student stu4 = new Student("10002","大乔","1000202",'女');
  Student stu5 = new Student("10002","小乔","1000203",'女');
  Student stu6 = new Student("10003","诸葛亮","1000301",'男');

  stuList.add(stu1);
  stuList.add(stu2);
  stuList.add(stu3);
  stuList.add(stu4);
  stuList.add(stu5);
  stuList.add(stu6);

  Map<String,List<Student>> collect = stuList.stream().collect(Collectors.groupingBy(Student::getClassId));
  for(Map.Entry<String,List<Student>> stuMap:collect.entrySet()){
     String classId = stuMap.getKey();
     List<Student> studentList = stuMap.getValue();
     System.out.println("classId:"+classId+",studentList:"+studentList.toString());
  }
}

As can be seen from the above data, stulist is divided into three groups. The key of each group is CLassID, and each CLassID corresponds to a student list. This makes it easy to separate the data; At this point, no matter how the data needs to be processed, it will be easy.

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. Thank you for your support.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>