天天看點

JDK1.8 List Stream流

一、準備

        有一個蘋果類,具有4個屬性。

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Apple {

    private Integer id;
    private String name;
    private BigDecimal money;
    private Integer num;

    public double money() {
        return this.money.doubleValue();
    }

    public static List<Apple> init() {
        List<Apple> appleList = new ArrayList<>();

        Apple apple1 = new Apple(1, "蘋果1", new BigDecimal("3.25"), 10);
        Apple apple12 = new Apple(1, "蘋果2", new BigDecimal("1.35"), 20);
        Apple apple2 = new Apple(2, "香蕉", new BigDecimal("2.89"), 30);
        Apple apple3 = new Apple(3, "荔枝", new BigDecimal("9.99"), 40);

        appleList.add(apple1);
        appleList.add(apple12);
        appleList.add(apple2);
        appleList.add(apple3);

        return appleList;
    }
}      

功能一:分組

根據ID進行分組

List<Apple> appleList = init();
        //(1)根據ID進行分組
        Map<Integer, List<Apple>> appleGroupById = 
                       appleList.stream().collect(Collectors.groupingBy(Apple::getId));      

功能二:過濾

過濾ID出ID為1的元素

List<Apple> collect = appleList.stream().filter(apple -> 
                               apple.getId().equals(1)).collect(Collectors.toList());      

過濾ID出ID不為1的元素

Set<Apple> set = appleList.stream().filter(apple -> 
                    !apple.getId().equals(1)).collect(Collectors.toSet());      

功能三:取某列元素

從List中取出某列元素

List<Integer> collect1 = 
                     appleList.stream().map(Apple::getNum).collect(Collectors.toList());
List<BigDecimal> collect = 
                     appleList.stream().map(Apple::getMoney).collect(Collectors.toList());      

功能四:計算(必須要加上健壯性判斷!)

計算最大、最小、個數、平均、求和

強烈注意:當集合為空的時候,最大值最小值将會出現不想要的數字,求平均也要特别注意分母為0的情況

IntSummaryStatistics intSummaryStatistics =
                appleList.stream().collect(Collectors.summarizingInt(Apple::getNum));

        System.out.println("max:" +intSummaryStatistics.getMax());
        System.out.println("min:" +intSummaryStatistics.getMin());
        System.out.println("sum:" + intSummaryStatistics.getSum());
        System.out.println("count:" +intSummaryStatistics.getCount());
        System.out.println("avg:" +intSummaryStatistics.getAverage());      

函數式接口

JDK1.8 List Stream流
JDK1.8 List Stream流
JDK1.8 List Stream流
JDK1.8 List Stream流