@Test
public void test18(){
List list = Arrays.asList(
new UserVo(1, "jack"),
new UserVo(2, "alice"),
new UserVo(3, "tom")
);
//以id为主键转为map
Map map = list.stream().collect(Collectors.toMap(UserVo::getId, Function.identity()));
System.out.println(map);
}
@Test
public void test19(){
List list = Arrays.asList(
new UserVo(1, "jack"),
new UserVo(2, "alice"),
new UserVo(2, "tom")
);
//以id为主键转为map
//给出key重复时,使用哪个key作为主键,以下代码中的(key1, key2) -> key2)代表key1和key2键重复时返回key2做主键
//{1=UserVo(id=1, name=jack), 2=UserVo(id=2, name=tom)}
Map map = list.stream().collect(Collectors.toMap(UserVo::getId, Function.identity(), (key1, key2) -> key2));
System.out.println(map);
}
@Test
public void test20(){
List list = Arrays.asList(
new UserVo(1, "jack"),
new UserVo(2, "alice"),
new UserVo(2, "tom")
);
// 不想返回对象,只返回对象里某个属性时 采用这种方式
Map map = list.stream().collect(Collectors.toMap(UserVo::getId, UserVo::getName, (key1, key2) -> key2));
System.out.println(map);
}
@Test
public void test21(){
List list = Arrays.asList(
new UserVo(1, "jack"),
new UserVo(2, "alice"),
new UserVo(2, "tom")
);
Map> map = list.stream().collect(Collectors.groupingBy(UserVo::getId));
System.out.println(map);
}