JDK 1.8收集器使用

weixin_33912246發表於2018-05-20

實體類定義:

@Data
public class User {

    private String userName;
    private int age;
    
    public User() {
    }
    
    
    public User(String userName, int age) {
        this.userName = userName;
        this.age = age;
    }
}

收集器使用案例:



    public static void main(String[] args) {
        List<User> list = new ArrayList<User>(
                Arrays.asList(
                        new User("TangLingYun", 28), 
                        new User("TangLingYun1", 21),
                        new User("TangLingYun2", 22), 
                        new User("TangLingYun4", 22), 
                        new User("TangLingYun3", 23)));

        // 資料提取
        TreeSet<Integer> treeSet = list.stream().map(User::getAge).collect(Collectors.toCollection(TreeSet::new));
        System.err.println(treeSet);

        // 聚合函式
        IntSummaryStatistics intSummaryStatistics = list.stream().collect(Collectors.summarizingInt(User::getAge));
        System.err.println(intSummaryStatistics);

        // 分塊 資料篩選
        Map<Boolean, List<User>> map = list.stream().collect(Collectors.partitioningBy(u -> u.getAge() < 28));
        System.err.println(map);

        // 分組
        Map<Integer, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getAge));
        System.err.println(collect);

        // 分組 個數
         Map<Integer, Long> collect2 = list.stream().collect(Collectors.groupingBy(User::getAge,Collectors.counting()));
        System.err.println(collect2);

    }


輸出結果:

[21, 22, 23, 28]
IntSummaryStatistics{count=5, sum=116, min=21, average=23.200000, max=28}
{false=[User@2d554825], true=[User@68837a77, User@6be46e8f, User@3567135c, User@327471b5]}
{21=[User@68837a77], 22=[User@6be46e8f, User@3567135c], 23=[User@327471b5], 28=[User@2d554825]}
{21=1, 22=2, 23=1, 28=1}

相關文章