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遍历
for (Map.Entry<String, XxxObject> entry : xxxMap0.entrySet()) {
String key = entry.getKey();
XxxObject val = entry.getValue();
}