巧用Stream:像sql一样操作数据集合
背景:
从数据库中查询出的数据,最各种运算。Stream最方便。
//转Map操作 实体中的2个字段,转为key=字段 value=字段
Map<String, Integer> collect = studentList.stream().collect(Collectors.toMap(Student::getGroupPointId, Student::getGroupStatus));
//转Map操作 key=某个字段,value=实体对象
Map<String, Student> studentDBMap = studentList.stream().collect(Collectors.toMap(Student::getGroupNo,v->v,(o,n)->n));
//分组统计,key-List
Map<Long, List<MapDic>> dicMap = mapDics.stream().collect(groupingBy(m -> m.getMapAreaId()));
//分组统计
Map<String, Long> storageCountMap = request.getStorageList().stream().collect(Collectors.groupingBy(Student::getAge, Collectors.counting()));
//多级分组 统计
Map<Long,Map<String,List<Student>>> map = points.stream().collect(groupingBy(e->e.getMapAreaId(),
groupingBy(e -> e.getLogicalCode()+"_"+e.getLogicalName())));
//转list
List<Stream> itemList = studentStreams.stream().map(this::getStreamObj).collect(Collectors.toList());
List<String> alleyNoStrList = alleyList.stream().map(Student::getAge).collect(Collectors.toList());
==========================================================================
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步