几种 Java8 中通过 Stream 的常用方法

项目场景:

缩减日常代码冗余


问题描述:

stream()的一些常用方法及使用场景


List<T>分组:

提示:查询数据库返回List<T>

List<AppAlarmRecord> list = appAlarmRecordMapper.selectFaultOverview();

根基T中的某个属性进行分组:

Map<String, List<AppAlarmRecord>> map = list.stream().collect(Collectors.groupingBy(AppAlarmRecord::getVin));

List转换Map:

提示:查询数据库返回List<T>

List<AppAlarmRecord> list = appAlarmRecordMapper.selectFaultOverview();

提示:List<T>转换Map<T.属性, T>:

Map<String,AppAlarmRecord> map1 = list.stream().collect(Collectors.toMap(AppAlarmRecord::getVin, a -> a,(k1,k2)->k2

获取List<T>中的某个属性生成新的数组List<T.属性>:

提示:查询数据库返回List<T>

List<AppAlarmRecord> list = appAlarmRecordMapper.selectAlarmByVin("123",null);

例如:

List<String> list1 = list.stream().map(AppAlarmRecord::getAlarmType).collect(Collectors.toList());


提示:T为JSONObject时:

List<JSONObject> list = new ArrayList<>();

JSONObject jsonObject = new JSONObject();

jsonObject.put("name","zhangsan");

jsonObject.put("age","20");

jsonObject.put("sex","nan")

list.add(jsonObject);

list.add(jsonObject);


例如:

   List<String> listName= list.stream().map(a -> {
       return a.get("name").toString();
   }).collect(Collectors.toList());

List<T1>转List<T2>:

提示:查询数据库返回List<T>

List<AppAlarmMileageStatisticSingleDAO> list = appAlarmMileageStatisticSingleMapper.selectAlarmStatistic();
例如:把T1中的某些值赋值给T2中的某些变量生成新的数组List<T2>

   List<AppAlarmStatisticVO> map = list.stream().map(appAlarmMileageStatisticSingleDAO -> {
       return  new AppAlarmStatisticVO(appAlarmMileageStatisticSingleDAO.getDrivingMileageRange(), appAlarmMileageStatisticSingleDAO.getAlarmSum());
   }).collect(Collectors.toList());

例如:获取List<T>中每个T中的两个属性生成 List<Map<T.属性1, T.属性1>>

去重:

提示:第一种方法我们通过新创建一个不同元素列表来实现根据对象某个属性去重

//查询返回结果List<T>
List<AppAlarmRecord> list = appAlarmRecordMapper.selectFaultRecord();
list.stream().collect(
                    collectingAndThen(
                            toCollection(() -> new TreeSet<>(Comparator.comparing(AppAlarmRecord::getVin))), ArrayList::new)
            );

例如:第二种通过filter()方法

首先创建一个方法作为 Stream.filter() 的参数,其返回值类型为Predicate,原理就是判断一个元素能否加入到Set中去,代码如下:

private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

使用如下:

//查询获取List<T>
List<AppAlarmRecord> listAppAlarmRecord = groupByProvinceCode.selectApp();

//调用distinctByKey(),根据vin去重
listAppAlarmRecord = listAppAlarmRecord.stream().filter(distinctByKey(AppAlarmRecord::getVin)).collect(Collectors.toList());

集合中对象的属性是否有某个值:

提示:

boolean b = list.stream().anyMatch(p -> p.age == 4);


例如:

 


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值