java Stream将List<Map<String,Object>>抽取字段

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());
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值