Java Stream常用代碼

// 過濾數據
List<TestVo> list= list.stream()
        .filter(x -> NumberUtil.isLessOrEqual(x.getPrice(), testVo.getPrice())) 
        .collect(Collectors.toList());

// 排序數據
List<TestVo> list= list.stream()
        .sorted(Comparator.comparing(TestVo::getPrice))
        .collect(Collectors.toList());

// 轉換map 指定key-value,value是對象中的某個屬性值
Map<BigDecimal, BigDecimal> maps = list.stream()
        .collect(Collectors.toMap(TestVo::getPrice, TestVo::getNumber, (k1, k2) -> k1));       

// 轉換map 指定key-value,value是對象本身
Map<BigDecimal, TestVo> maps = list.stream()
        .collect(Collectors.toMap(TestVo::getPrice, Function.identity(), (k1, k2) -> k1));

// 求和
BigDecimal maps = list.stream()
                // 將TestVo對象的price取出來map爲Bigdecimal
                .map(TestVo::getPrice)
                // 使用reduce()聚合函數,實現累加器
                .reduce(BigDecimal.ZERO, BigDecimal::add);
                
// 根據Bean的某個字段分組
Map<String, List<TestVo>> map = emps.stream()
    	.collect(Collectors.groupingBy(TestVo::getCity));
                
// 取出單個元素放入集合中
List<String> newlist = list.stream().map(TestVo::getCity).collect(Collectors.toList());

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章