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

函数式接口

 

 

posted @ 2022-07-17 12:13  小大宇  阅读(104)  评论(0编辑  收藏  举报