1. 程式人生 > >JDK1.8 Stream 資料流 的一些例子

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();//總共花費

    }
}