List<Map<String,Object>> decompList = dao.query(sql1); 1.按某个字段抽取为List<String>
List<String> ListName = decompList.stream().map(e -> e.get("NAME").toString()).collect(Collectors.toList());
2.按2个字段,抽取为Map<String,Object>
Map<String, Object> decompMap = decompList.stream()
.collect(Collectors.toMap(e -> Optional.ofNullable((String)e.get("ID_")).orElse(null),e -> Optional.ofNullable(e.get("NAME")).orElse("")));
3.list转map 当map的value值为空时会报错空指针异常(InvocationTargetException),有以下两种处理方式:
//解决方案一,使用Optional类处理null
HashMap<String, String> cityProvinceMap = cityProvinceList.stream().collect(Collectors.toMap(s -> Optional.ofNullable(s.getCityName()).orElse(null), s -> Optional.ofNullable(s.getProvince()).orElse("unknown"), (a, b) -> b, HashMap::new));
//解决方案二,直接使用collect()方法进行规约操作
HashMap<String, String> cityProvinceMap2 = cityProvinceList.stream().collect(HashMap::new, (map, item) -> map.put(item.getCityName(), item.getProvince()), HashMap::putAll);
4.list空字段排序:
if("asc".equals(bo.getOrderType())){
orderList = orderList.stream().sorted(Comparator.comparing(CompanyListingStatisticsModel::getPeTtm, Comparator.nullsLast(Comparator.naturalOrder()))).collect(Collectors.toList());
}else{
orderList = orderList.stream().sorted(Comparator.comparing(CompanyListingStatisticsModel::getPeTtm, Comparator.nullsLast(Comparator.reverseOrder()))).collect(Collectors.toList());
}