jdk1.8中stream流的日常使用

一.前言

本文主要讲解stream流在日常中经常使用的场景,以及解决策略。

二.stream流日常用法

1.reduce累积求和

BigDecimal reduce = pList.stream().map(Person::getSalary).reduce(BigDecimal.ZERO, BigDecimal::add);

2.collect累积求和

//                               集合                        求和函数 (double/long都有)
IntSummaryStatistics collect = list.stream().collect(Collectors.summarizingInt(e -> Integer.parseInt(e)));
//                           集合元素个数  求和    最小值    平均值            最大值 
// 输出结果为:IntSummaryStatistics{count=2, sum=3, min=1, average=1.500000, max=2},通过get方法获取值

3.map累积和

BigDecimal bigDecimal = BigDecimal.valueOf(list.stream().mapToDouble(e -> Double.parseDouble(e)).sum()).setScale(2, BigDecimal.ROUND_HALF_DOWN);

4.collect的用法

4.1toList:将原来的Stream映射为一个单元素流,然后收集为List

List<String> names = dishes.stream().map(Dish::getName).collect(toList());

4.2toSet:将Type收集为一个set,可以去重复

Set<Type> types = dishes.stream().map(Dish::getType).collect(Collectors.toSet());

4.3toMap:有时候可能需要将一个数组转为map,做缓存,方便多次计算获取。toMap提供的方法k和v的生成函数。

Map<Type, Dish> byType = dishes.stream().collect(toMap(Dish::getType, d -> d));

4.4list转换成map

Map<String,String> map=list.stream().collect(Collectors.toMap(BudgetFundsType::getGrade, BudgetFundsType::getCode));

5.groupingBy,查询出list<map>中某一个键值重复次数

Map<Object, Long> repetitionRemark = dataMap.stream().collect(Collectors.groupingBy(a -> a.get("remark"), Collectors.counting()));

6.使用groupingBy按照grade进行分组

Map<Integer, List<BudgetFundsType>> gradeMap = list.stream().collect(Collectors.groupingBy(BudgetFundsType::getGrade))

7.将com.alibaba.fastjson.JSONObject转化为hashmap

JSONObject obj = new JSONObject();
obj.put("key1", "a");
obj.put("key3", "c");
Map<String, String> params = JSONObject.parseObject(obj.toJSONString(),new TypeReference<Map<String, String>>(){});

8.按键降序排序(加reversed升序)(去除reversed降序)

public <K extends Comparable<? super K>, V> Map<K, V> descSortByKey(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();
    //                       排序                   键排序方法        反转        遍历结果             输出结果至新的Map集合中
    map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByKey().reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
    return result;
}

9.按值升序排序(加reversed升序)(去除reversed降序)

public <K, V extends Comparable<? super V>> Map<K, V> ascSortByValue(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();
    //                       排序                   值排序方法        遍历结果             输出结果至新的Map集合中
    map.entrySet().stream().sorted(Map.Entry.<K, V>comparingByValue()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
    return result;
}

10.List<对象>排序

Collections.sort(list, Comparator.comparing(JxFormStructure::getOldfieldName));

11.List<对象>连续排序

list.stream().sorted(Comparator.comparing(PdUnifiedVoucherBody::getMergeField).thenComparing(PdUnifiedVoucherBody::getDirection)).collect(Collectors.toList())

12.List<对象>多属性拼接排序

list.stream().sorted(Comparator.comparing(a -> a.getAssistAccounting() +"-" + a.getDeptName() +"-" + ("0".equals(String.valueOf(a.getDebitMoney())) ? a.getCreditMoney() : a.getDebitMoney()))).collect(Collectors.toList())

13.Map转List<map<String,Object>>

Map<String, Object> map = new HashMap<>();
map.entrySet().stream().collect(Collectors.toList())

14.替换集合中某个属性的值

list.stream().forEach(a -> a.setPeriod(period))

15.List<Map>或List<对象>根据其中某一个属性去重

/**
 * List<Map>中某个属性去重
 */
public class ListMapDistinctUtils<T> {
    /**
     * 1.单个属性去重:
     * List<Map>使用实例:List<Map<String, Object>> newListMap=listMaps.stream().filter(ListMapDistinctUtils.distinctByKey(a->a.get("assessmentMode"))).collect(Collectors.toList())
     * List<对象>使用实例:List<TestCommodity> codeDistinctList = testCommodityList.stream().filter(distinctByKey(TestCommodity::getCode)).collect(Collectors.toList());
     * 2.多个属性去重:distinctByKey中传两个属性的拼接值
     * 3.其他方法多属性去重:List<TestCommodity> cbList = testCommodityList.().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(tc -> tc.getCode() + ";" + tc.getBarCode()))), ArrayList::new));
     *
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> concurrentHashMap = new ConcurrentHashMap<>();
        return t -> concurrentHashMap.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}

16.实体中字段为null排序(nullsFirst/nullsLast)

list.sort(Comparator.comparing(YsProjectList::getLoanAmount,Comparator.nullsFirst(Double::compareTo)));
              //实体         //排序字段                  //空值在前         //字段数据类型

17.实体为null的情况

list.sort(Comparator.nullsLast(Comparator.comparing(YsProjectList::getLoanAmount,Comparator.nullsLast(Double::compareTo))));

18.获取集合中最大值对象

list.stream().max(Comparator.comparing(FacilityManagementData::getParamValue)).get();

三.总结

以上是博主stream流的常用用法,后续比较复杂的用法会进行同步更新

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

任性的代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值