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