package stream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author zzl
* @Date 2022/1/15
* @description Java stream特性:Collectors.toMap
*/
public class CollectorsToMapTest {
public static void main(String[] args) {
List<TestVo> testList = new ArrayList<>();
// 初始化list
for (int i = 0; i < 3; i++) {
TestVo vo = new TestVo();
vo.setUserId(i);
vo.setName(UUID.randomUUID().toString().replaceAll("-", ""));
testList.add(vo);
}
// toMap(p1,p2),p1参数是map的key值,p2参数是map的value值,当value为对象时,可以用Function.identity()表示value值
Map<Integer, String> map = testList.stream().collect(Collectors.toMap(TestVo::getUserId, TestVo::getName));
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());
}
System.out.println("==================================================");
testList = new ArrayList<>();
testList.add(new TestVo(1, "a"));
testList.add(new TestVo(2, "b"));
testList.add(new TestVo(1, "c"));
// toMap(p1,p2,p3),其中p3参数是为了解决key值冲突时,决定value取值的
Map<Integer, String> map2 = testList.stream()
.collect(Collectors.toMap(TestVo::getUserId, TestVo::getName, (oldValue, newValue) -> oldValue));
System.out.println("(oldValue, newValue) -> oldValue的方式:key值冲突时,value取值为旧的key对应的value值");
map2.forEach((k, v) -> System.out.println("key=" + k + ",value=" + v));
System.out.println("(oldValue, newValue) -> newValue的方式:key值冲突时,value取值为新的key对应的value值");
map2 = testList.stream()
.collect(Collectors.toMap(TestVo::getUserId, TestVo::getName, (oldValue, newValue) -> newValue));
map2.forEach((k, v) -> System.out.println("key=" + k + ",value=" + v));
}
}
执行结果 :
key=0,value=acd45a638a2b43a4b7ccab7781290916
key=1,value=6fa7e201faaf4de0b4d6645214966285
key=2,value=468721a42ff14dc38a0b4efd2bf288eb
==================================================
(oldValue, newValue) -> oldValue的方式:key值冲突时,value取值为旧的key对应的value值
key=1,value=a
key=2,value=b
(oldValue, newValue) -> newValue的方式:key值冲突时,value取值为新的key对应的value值
key=1,value=c
key=2,value=b
package stream;
/**
* @author zzl
* @Date 2022/1/15
* @description
*/
public class TestVo {
private Integer userId;
private String name;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public TestVo(Integer userId, String name) {
this.userId = userId;
this.name = name;
}
public TestVo() {
}
}