12.01 java jdk1.8 使用stream流進行list 分組歸類


java jdk1.8 使用stream流進行list 分組歸類

哈哈,當我還是學生時自學PS披的第一張圖就拿來發布第一篇文章


在日常工作中我們都會遇到將數據進行分組的需求

  • 那麼在Java 中如何將簡單又方便的將list集合進行分組呢?
  • 在java8特性中我們可以使用stream流很方便的對集合進行操作
  • 下面將以兩種方式進行分組操作(java8中還有其他操作可以分組,這裡只介紹兩種,其他方式大同小異)

list 分組歸類代碼

import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author caizw
*/
public class Foo {
private String name;
private String type;
private Double typeValue;
private Integer count;

public Foo(String name, String type, Double typeValue, Integer count) {
this.name = name;
this.type = type;

this.typeValue = typeValue;
this.count = count;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getType() {
return type;
}

public void setType(String type) {
this.type = type;
}

public Double getTypeValue() {
return typeValue;
}

public void setTypeValue(Double typeValue) {
this.typeValue = typeValue;
}

public Integer getCount() {
return count;
}

public void setCount(Integer count) {
this.count = count;
}

@Override
public String toString() {
return "Foo{" +
"name='" + name + '\\'' +
", type='" + type + '\\'' +
", typeValue=" + typeValue +
", count=" + count +
'}';
}

public static void main(String[] args) {
List fooList = new ArrayList<>();
fooList.add(new Foo("A", "san", 1.0, 2));

fooList.add(new Foo("A", "nas", 13.0, 1));
fooList.add(new Foo("B", "san", 112.0, 3));
fooList.add(new Foo("C", "san", 43.0, 5));
fooList.add(new Foo("B", "nas", 77.0, 7));
List<list>> groupList = new ArrayList<>();

// 分組方式一
fooList.stream()
.collect(Collectors.groupingBy(Foo::getName, Collectors.toList()))
.forEach((name, fooListByName) -> {
groupList.add(fooListByName);
});
\t
// 分組方式二
Map<string>> groupMap = fooList.stream().collect(Collectors.groupingBy(Foo::getName));

System.out.println(JSON.toJSONString(groupList));

System.out.println(JSON.toJSONString(groupMap));
}
}/<string>/<list>

輸出結果:

  • groupList
[
[
{
"count": 2,
"name": "A",
"type": "san",
"typeValue": 1
},
{
"count": 1,
"name": "A",
"type": "nas",
"typeValue": 13
}
],
[
{
"count": 3,

"name": "B",
"type": "san",
"typeValue": 112
},
{
"count": 7,
"name": "B",
"type": "nas",
"typeValue": 77
}
],
[
{
"count": 5,
"name": "C",
"type": "san",
"typeValue": 43
}
]
]
  • groupMap
{
"A": [
{
"count": 2,
"name": "A",
"type": "san",
"typeValue": 1
},
{
"count": 1,
"name": "A",
"type": "nas",
"typeValue": 13
}
],
"B": [
{
"count": 3,
"name": "B",
"type": "san",
"typeValue": 112
},
{
"count": 7,
"name": "B",

"type": "nas",
"typeValue": 77
}
],
"C": [
{
"count": 5,
"name": "C",
"type": "san",
"typeValue": 43
}
]
}

剛入駐今日頭條,感興趣對童鞋可以關注本作者。後期會慢慢分享一些教程以及經驗。打算後期為大家寫一個簡易的微服務教程,以及作者使用微服務在開發中遇到的一些問題,以及怎麼解決的經驗分享給大家!自動化部署項目等


分享到:


相關文章: