1. 程式人生 > 程式設計 >java8 stream的分組功能例項介紹

java8 stream的分組功能例項介紹

前言

最近,專案開發時遇到一個問題。根據業務要求,前端給後端上送的引數是一個列表(如List list),因此,後端也用了一個列表來接收。然而,等後端拿到資料後,我發現我需要對相同classId的資料進行統一處理。於是,我找到前端妹妹討論,看她能不能幫忙把相同classId的資料封裝成列表傳給我。我好將接收引數修改成以下格式(List list):

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

這時,前端妹妹評估了下改動程度,眼淚汪汪地看著我

我瞬間明白了,我表現的機會到了!

我說道:這樣吧!前端不動,後端來處理!

後端不能說不行!

仔細看了下資料,運用java 8 stream分組功能輕鬆解決。

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());
  }
}

classId:10002,studentList:[Student [classId=10002,name=劉備,studentId=1000201,age=16,sex=男],Student [classId=10002,name=大喬,studentId=1000202,sex=女],name=小喬,studentId=1000203,sex=女]]
classId:10001,studentList:[Student [classId=10001,name=孫權,studentId=1000101,Student [classId=10001,name=曹操,studentId=1000102,sex=男]]
classId:10003,studentList:[Student [classId=10003,name=諸葛亮,studentId=1000301,sex=男]]

從上面的資料可以看出來,stuList被分成了三個組,每個組的key都是classId,而每個classId都對應一個學生列表,這樣就很輕鬆地實現了資料的分離;此時,無論需要對資料進行怎樣的處理都會很容易。

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對我們的支援。