GroupingBy两个参数的用法示例


import lombok.AllArgsConstructor;
import lombok.Data;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * GroupingBy两个参数的用法示例
 */
public class CollectorsGroupingByDemo {
    List<Lis> list = Arrays.asList(new Lis("a", "111", "12"),
            new Lis("b", "222", "13"), new Lis("c", "333", "15"),
            new Lis("a", "444", "11"), new Lis("a", "555", "13"),
            new Lis("b", "666", "12"), new Lis("c", "777", "14")
    );

    @Test
    public void test() {
        Map<String, String> map = list.stream().collect(Collectors.groupingBy(Lis::getName, Collectors.mapping(Lis::getAge, Collectors.joining(","))));
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "====" + entry.getValue());
        }
        //a====12,11,13
        //b====13,12
        //c====15,14
    }

    @Data
    @AllArgsConstructor
    static class Lis {
        private String name;
        private String value;
        private String age;
    }
}
posted @ 2020-07-27 09:02  fly_bk  阅读(4473)  评论(0编辑  收藏  举报