在业务档口由于得到的数据全是 List<Map<String,Object>>由于最终要返回的数据全是 List<Map<String,String>>使用foreach和map.entrySet()来进行转换效率有点低,有木有更好的解决方案
1 回答
月关宝盒
注意:业务方法用
TA贡献1772条经验 获得超5个赞
这个简单
可以并行stream+map+collector很方便
代码的话,我现在不方便敲代码,有时间给你补上,但是需要你们的项目支持jdk8
更新(抱歉,刚上班,给你写了一下,你看看和你的业务匹配吗,另外试下效率,当然,还有改进的空间...)
注意:业务方法用private修饰,避免暴露
public class Test { public static void main(String[] args) { // 构造参数
List<Map<String, Object>> input = new ArrayList<Map<String, Object>>() {{ add(Collections.singletonMap("one", 1)); add(Collections.singletonMap("two", 2)); add(Collections.singletonMap("three", 3));
trimToSize();
}}; // 开始转换
List<Map<String,String>> output = input.parallelStream().map(Test::convert).collect(toList()); // 验证
output.forEach(m->{
m.forEach((k, v)-> System.out.println(k + "\t" + v));
});
} /**
* 业务
* */
private static Map<String, String> convert(Map<String, Object> map) {
Objects.requireNonNull(map);
Map<String, String> result = new ConcurrentHashMap<>(map.size()); // 业务比较繁杂的,可以用compute方法
map.forEach((key, value) -> result.put(key, value.toString())); return result;
}
}添加回答
举报
0/150
提交
取消
