public class YebTest {
List<User> userList = new ArrayList<User>(){{
add( new User("A","张三"));
add( new User("A","李四"));
add(new User("C","王五"));
}};
/**
* A->张三
* B->李四
* C->王五
*
* java.lang.IllegalStateException: Duplicate key com.taimeitech.app.edc.app.api.web.cdisc.User@5e5792a0
*/
@Test
public void test1(){
Map<String, String> map = userList.stream().collect(Collectors.toMap(User::getId, User::getName));
map.forEach((key,value) -> {
System.out.print(key + "->");
System.out.println(value);
});
}
/**
* A->A张三
* B->B李四
* C->C王五
*
* java.lang.IllegalStateException: Duplicate key com.taimeitech.app.edc.app.api.web.cdisc.User@5e5792a0
*/
@Test
public void test2(){
// Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getId, t -> t));
Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
map.forEach((key,value) -> {
System.out.print(key + "->");
System.out.println(value.getId() + value.getName());
});
}
/**
* A->A张三
* C->C王五
*/
@Test
public void test3(){
// Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getId, t -> t));
Map<String, User> map = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(t1,t2) -> t1));
map.forEach((key,value) -> {
System.out.print(key + "->");
System.out.println(value.getId() + value.getName());
});
}
/**
* A->张三
* 李四
* C->王五
*/
@Test
public void test4(){
// Map<String, String> map = userList.stream().collect(Collectors.toMap(User::getId, User::getName, (t1,t2) -> t1 + t2));
Map<String, List<User>> map = userList.stream().collect(Collectors.groupingBy(t -> t.getId()));
map.forEach((key,value) -> {
System.out.print(key + "->");
List<String> collect = value.stream().map(user -> user.getName()).sorted().collect(Collectors.toList());
collect.stream().forEach(System.out::println);
});
}
}
stream分组API
最新推荐文章于 2024-07-16 15:36:11 发布
这篇博客探讨了Java中使用Stream API处理List时遇到的重复键问题,通过不同方式解决冲突,包括使用`toMap`的合并函数。测试用例展示了如何将用户列表转换为Map,以及如何进行分组操作。测试结果强调了在处理Map时避免重复键的重要性。
摘要由CSDN通过智能技术生成