我想轉換一個Map<String, List<MyObject>> to List<Map<String, MyObject>>
轉換地圖<字符串,列表<MyObject>爲List <地圖<字符串,爲MyObject >>在Java中
{<key1,[myObject1, myObject2]>, <key2,[myObject3, myObject4]>} will be converted to [{<key1,myObject1>, <key2,myObject3>}, {<key1,myObject2>, <key2, myObject4>}]
其中myObject1和myObject3具有相同的唯一的ID等做myObject2和myObject4。
我的實現在下面,但有沒有更好的方式來做到這一點。
private List<Map<String, MyObject>> getObjectMapList(Map<String, List<MyObject>> objectMap)
{
List<Map<String, MyObject>> objectMapList = new ArrayList<Map<String,MyObject>>();
for(MyObject myObject : objectMap.get("key1")) {// there will be default key1 whose value is known
Map<String, MyObject> newMap= new HashMap<String, MyObject>();
for (String key : objectMap.keySet()) {
newMap.put(key, objectMap.get(key).stream()
.filter(thisObject -> thisObject.getId().equals(myObject.getId()))
.collect(Collectors.toList()).get(0));
}
objectMapList.add(newMap);
}
return objectMapList;
}
哪裏了'language'變量從何而來? – Jeff
是一些錯字。編輯它 – user3330263