stream分组API

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);
        });
    }
}

猜你喜欢

转载自blog.csdn.net/kunAUGUST/article/details/119417362