1. 程式人生 > >Java 8 流過濾List

Java 8 流過濾List

// 獲得小於18歲的使用者物件

List<User> list = userList.stream().filter(o ->o.getAge()<18).collect(Collectors.toList());

//獲得小於18歲的使用者名稱字


List<String> list = userList.stream() .filter(o -> o.getAge()<18)
                    .map(User::getName).collect(Collectors.toList());

// 獲得身份證為key,使用者物件為value的map

Map<String,User> userMap = userList.stream().collect(Collectors.toMap(o -> o.getIdNumber(), o -> o));

// 通過名字分組

Map<String,List<User>> map = userList.stream()
                .collect(Collectors.groupingBy(o -> o.getName()));

// 去重

insertList = insertList.stream().collect(Collectors.toSet()).stream().collect(Collectors.toList());


// 使用者按建立年份分組


Map<Date,List<User>> userList = list.stream().collect(Collectors.groupingBy(o->DateUtil.getCurrYearFirst(o.getCreateDate())));//DateUtil.getCurrYearFirst()返回的是時間的年份

// 計算合計

Double totalSale = saleList.stream().filter(o -> o.getMoney() != null).mapToDouble(a -> a.getMoney()).sum();

這個是網上抄的關於計算

// 獲取數字的個數、 最小值、 最大值、 總和以及平均值
            List<Integer> list = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
            //IntSummaryStatistics:集合概要例如: count, min, max, sum, and average.
            IntSummaryStatistics stats = list//
                    .stream()//獲取Stream物件
                    .mapToInt((x) -> x)//格式轉換
                    .summaryStatistics();//
            System.out.println("Max : " + stats.getMax());
            System.out.println("Min: " + stats.getMin());
            System.out.println("Sun: " + stats.getSum());
            System.out.println("Average : " + stats.getAverage());
--------------------- 
原文:https://blog.csdn.net/qq_15988951/article/details/53914146 


 

遇到在持續更新!