欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java8 stream的分組功能實(shí)例介紹

 更新時(shí)間:2019年12月29日 15:28:34   作者:一輩子的碼農(nóng)先生  
這篇文章主要給大家介紹了關(guān)于java8 stream的分組功能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用java8具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

前言

最近,項(xiàng)目開發(fā)時(shí)遇到一個(gè)問題。根據(jù)業(yè)務(wù)要求,前端給后端上送的參數(shù)是一個(gè)列表(如List list),因此,后端也用了一個(gè)列表來(lái)接收。然而,等后端拿到數(shù)據(jù)后,我發(fā)現(xiàn)我需要對(duì)相同classId的數(shù)據(jù)進(jìn)行統(tǒng)一處理。于是,我找到前端妹妹討論,看她能不能幫忙把相同classId的數(shù)據(jù)封裝成列表傳給我。我好將接收參數(shù)修改成以下格式(List list):

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

這時(shí),前端妹妹評(píng)估了下改動(dòng)程度,眼淚汪汪地看著我

我瞬間明白了,我表現(xiàn)的機(jī)會(huì)到了!

我說(shuō)道:這樣吧!前端不動(dòng),后端來(lái)處理!

后端不能說(shuō)不行!

仔細(xì)看了下數(shù)據(jù),運(yùn)用java 8 stream分組功能輕松解決。

public static void testStreamGroup(){
  List<Student> stuList = new ArrayList<Student>();
  Student stu1 = new Student("10001", "孫權(quán)", "1000101", 16, '男');
  Student stu2 = new Student("10001", "曹操", "1000102", 16, '男');
  Student stu3 = new Student("10002", "劉備", "1000201", 16, '男');
  Student stu4 = new Student("10002", "大喬", "1000202", 16, '女');
  Student stu5 = new Student("10002", "小喬", "1000203", 16, '女');
  Student stu6 = new Student("10003", "諸葛亮", "1000301", 16, '男');

  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, age=16, sex=女], Student [classId=10002, name=小喬, studentId=1000203, age=16, sex=女]]
classId:10001,studentList:[Student [classId=10001, name=孫權(quán), studentId=1000101, age=16, sex=男], Student [classId=10001, name=曹操, studentId=1000102, age=16, sex=男]]
classId:10003,studentList:[Student [classId=10003, name=諸葛亮, studentId=1000301, age=16, sex=男]]

從上面的數(shù)據(jù)可以看出來(lái),stuList被分成了三個(gè)組,每個(gè)組的key都是classId,而每個(gè)classId都對(duì)應(yīng)一個(gè)學(xué)生列表,這樣就很輕松地實(shí)現(xiàn)了數(shù)據(jù)的分離;此時(shí),無(wú)論需要對(duì)數(shù)據(jù)進(jìn)行怎樣的處理都會(huì)很容易。

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論