目录
一、主程序
二、辅助类
三、其他辅助类
四、执行结果
package xyz.jangle.thread.test.n6_4.collect;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import xyz.jangle.thread.test.n6_2.create.Person;
import xyz.jangle.thread.test.n6_2.create.PersonGenerator;
/**
* 6.4、收集流
*
* @author jangle
* @email [email protected]
* @time 2020年9月3日 下午9:27:11
*
*/
public class M {
public static void main(String[] args) {
// 1、收集成一个Map
List persons = PersonGenerator.generatePersonList(100);
ConcurrentMap> personByName = persons.parallelStream()
.collect(Collectors.groupingByConcurrent(Person::getFirstName));
// 遍历这个Map,并打印相关信息
personByName.keySet().forEach(key -> {
List list = personByName.get(key);
System.out.println(key + " : " + list.size());
});
// 2、串联方式收集
String resultName = persons.parallelStream().map(p -> p.toString()).collect(Collectors.joining(","));
System.out.println("串联方式收集的名称:" + resultName);
// 3、拆分为2组 薪资大于50000 和小于等于50000的
Map> part = persons.parallelStream()
.collect(Collectors.partitioningBy(p -> p.getSalary() > 50000));
part.keySet().forEach(k -> {
List list = part.get(k);
System.out.println(k + ":" + list.size());
});
// 4、收集成一个Map (firstName作key, LastName做value ,当存在相同的key时,将2个value用s1+","+s2的方式拼接
Map map = persons.parallelStream()
.collect(Collectors.toMap(p -> p.getFirstName(), p -> p.getLastName(), (s1, s2) -> s1 + "," + s2));
map.forEach((k, v) -> {
System.out.println(k + ":" + v);
});
// 5、并行处理列表,再合并列表
ArrayList
package xyz.jangle.thread.test.n6_4.collect;
/**
* 辅助类
* @author jangle
* @email [email protected]
* @time 2020年9月3日 下午9:28:51
*
*/
public class Counter {
private String value;
private int counter;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
public synchronized void increment() {
counter++;
}
}
https://blog.csdn.net/Bof_jangle/article/details/108350870
A : 12
B : 14
C : 12
D : 15
E : 15
F : 12
G : 20
串联方式收集的名称:D T,F Y,F X,G Y,D X,G Y,A Z,D T,G U,C Z,G Z,F V,B T,A W,E T,G Z,B U,F U,C Y,F Y,A X,G W,E W,E Y,E V,E Z,B Z,A W,C T,G X,G Y,D V,E T,C T,D T,B Y,G V,C X,E V,A U,C X,B X,E V,D U,C T,E W,E V,G Z,B V,B T,F V,E U,A Z,B T,G T,C U,B U,A V,G X,C W,G W,E W,F Z,F T,B Y,B Z,D Y,E Y,B T,E X,A T,E V,G Z,C T,D Z,D Z,A X,D Z,F Y,G X,G T,D V,D V,A V,B T,F Z,B Z,D V,A U,D T,G V,A T,G W,C U,C T,G T,F W,D T,G X,F X
false:50
true:50
A:Z,W,X,W,U,Z,V,T,X,V,U,T
B:T,U,Z,Y,X,V,T,T,U,Y,Z,T,T,Z
C:Z,Y,T,T,X,X,T,U,W,T,U,T
D:T,X,T,V,T,U,Y,Z,Z,Z,V,V,V,T,T
E:T,W,Y,V,Z,T,V,V,W,V,U,W,Y,X,V
F:Y,X,V,U,Y,V,Z,T,Y,Z,W,X
G:Y,Y,U,Z,Z,W,X,Y,V,Z,T,X,W,Z,X,T,V,W,T,X
高新人数:50
A:0
B:2
C:1
D:3
E:1
F:2
G:4