项目场景:
缩减日常代码冗余
问题描述:
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);
例如: