stream分组API

这篇博客探讨了Java中使用Stream API处理List时遇到的重复键问题,通过不同方式解决冲突,包括使用`toMap`的合并函数。测试用例展示了如何将用户列表转换为Map,以及如何进行分组操作。测试结果强调了在处理Map时避免重复键的重要性。
摘要由CSDN通过智能技术生成
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);
        });
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值