Java List和Map常用转换处理

List转Map

  • list转map(mapKey=id,mapValue = 对象本身)
// List<XxxObject> xxxList = new ArrayList<>(); //XxxObject中有id和name字段
Map<String, XxxObject> xxxMap0 = xxxList.stream().collect(Collectors.toMap(XxxObject::getId, o->o));
  • list转map(mapKey=id,mapValue = name)
 Map<String,String> xxxMap1 = xxxList.stream().collect(Collectors.toMap(XxxObject::getId,XxxObject::getName));
  • list转mapkey 冲突的解决办法,这里选择第二个key覆盖第一个key。Function.identity()是简洁写法,也是返回对象本身
Map<String,XxxObject> xxxMap2 = xxxList.stream().collect(Collectors.toMap(XxxObject::getId, Function.identity(),(key1,key2)->key2));

List filter过滤

  • 去掉xxxList中XxxObject的name=xxxx的数据
xxxList = xxxList.stream().filter(s->!s.getName().equals("xxxx")).collect(Collectors.toList());

取出List的ID用逗号隔开

  String ids = list.stream().map(XxxObject::getId).collect(Collectors.joining(","));

Map遍历

  • Map.Entry遍历得到key和value
for (Map.Entry<String, XxxObject> entry : xxxMap0.entrySet()) {
  String key = entry.getKey();
  XxxObject val = entry.getValue();
}
posted @ 2021-12-28 10:29  JaminX86  阅读(949)  评论(0编辑  收藏  举报