JDK1.8 Stream 数据流 的一些例子

定义购物车类

/**
 * @author 向振华
 * @date 2018/11/14 16:47
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ShopCar {

    /**
     * 商品名
     */
    private String name;

    /**
     * 单价
     */
    private Double price;

    /**
     * 数量
     */
    private Integer count;
    
}

测试类

/**
 * @author 向振华
 * @date 2018/11/14 16:48
 */
public class Test {

    /**
     * 创建购物车
     * @return
     */
    private static List<ShopCar> build(){
        return Lists.newArrayList(
                new ShopCar("苹果", 3.3, 10),
                new ShopCar("香蕉", 4.4, 20),
                new ShopCar("橘子", 5.5, 30)
                );
    }

    public static void main(String[] args) {
        List<ShopCar> shopCars = build();

        //按价格升序
        shopCars.sort((o1, o2) -> o2.getPrice().compareTo(o1.getPrice()));
        //按价格降序
        shopCars.sort((o1, o2) -> o1.getPrice().compareTo(o2.getPrice()));
        shopCars.sort(Comparator.comparing(ShopCar::getPrice));

        //取出集合中的某字段封装在list
        List<String> collect1 = shopCars.stream().map(ShopCar::getName).collect(Collectors.toList());

        //取出集合中两个字段封装在map
        Map<String, Integer> collect2 = shopCars.stream().collect(Collectors.toMap(ShopCar::getName, ShopCar::getCount));

        //将集合中数据计算后封装在map
        Map<String, Double> collect3 = shopCars.stream().collect(Collectors.toMap(ShopCar::getName, s -> s.getPrice() * s.getCount()));

        //统计出总价格
        Double allPrice = shopCars.stream().map(s -> s.getPrice() * s.getCount()).reduce((sum, p) -> sum + p).get();

        //统计操作
        DoubleSummaryStatistics dss = shopCars.stream().mapToDouble(s -> s.getPrice() * s.getCount()).summaryStatistics();
        dss.getCount();//商品个数
        dss.getAverage();//平均花费
        dss.getMax();//最高花费
        dss.getMin();//最低花费
        dss.getSum();//总共花费

    }
}

猜你喜欢

转载自blog.csdn.net/Anenan/article/details/84070620