List的基础数据的处理

286 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第2天,点击查看活动详情

List的基础数据的交互

在任务开发的过程中,我们会用到很多基于集合的操作,其中list集合我们用得很多,但是大多数是基于集合的数据操作,比如想转化另一个数据的集合,或者是蒋户数集合获取最大值的某个对象,以及过滤出我们需要的数据,又或者是想让把数据去重的操作,等等,我们在开发业务的过程中都会出现;

这次我们就来细节聊聊基于list的基本操作,基于stream流的操作可以借鉴架构悟空的

# 吃透JAVA的Stream流操作,多年实践总结, 我们来展示一下可能会遇见的常见情况;属于stream的补充

场景一:

List集合中,需要查询当前某个对象的某个字段数据最大值,最小值

本质上就是最大值、最小值,list寻找某个对象中属性最大的一个对象;

 List<DataVo> dataVoList=new arrayList();
 //最大值
 DataVo mongoMax =  .stream().max(Comparator.comparing(DataVo::getResultDouble)).get();
 //最小值
 DataVo mongoMin = dataVoList.stream().min(Comparator.comparing(DataVo::getResultDouble)).get();

场景二:

List集合中,需要去掉其他重复的元素活对象,用于统计

stream()流操作

  List<String> collect2 = oneDayTempMongoVoList.stream().map(c -> {
            return c.getHour();
        }).distinct().collect(Collectors.toList());      
                   

set去重也可以:

 List<String> listNew = new ArrayList<String>(new TreeSet<String>(list));

场景三:

List集合中,需要对其中的对象元素,基于某个属性进行排序(比如时间日期等)


 List<DataVo> dataVoList=new arrayList();
 
 dataVoList = dataVoList.stream().sorted(Comparator.comparing((DataVo::getDataTime))).collect(Collectors.toList());

场景四:

List集合中,需要分组,多种数据类型,需要统计,转换成map数据


 List<DataVo> dataVoList=new arrayList();
   Map<String, List<DataVo>> collect = dataVoList.stream().collect(Collectors.groupingBy(DataVo::getHour));

场景四:

List集合中,需要对对象元素进行模糊查询

可以使用contains()

    List<EqPredictStation> hotSourList = predictStationService.list().stream().filter(w -> w.getCollectGroupName().contains(HOTSOURCE)).collect(Collectors.toList());

list对某个字段模糊查询:

List<PredictEnergyVo> collect = collect.stream().filter(n -> Boolean.FALSE ? n.getCollectGroupName().equals(param.getCollectGroupName()) :
                   n.getCollectGroupName().contains(param.getCollectGroupName())).collect(Collectors.toList());