[英]How to convert LIst<Object> to Map<K, V> with using java stream
我想將List<ObjectInList>
轉換為Map<K, V>
class ObjectInList {
List<Long> listWithLong;
Map<String, Object> dataMap; // there is 'id' key, and i want to use this id as key in map to be converted
}
新的 map 格式如下
String type; // this type is value of dataMap.
List<Long> contents
List<Object>
中的每個 Object 都可以有重復的類型
例如
///////// before converted ////////////
[
{
list: [1,2,3],
dataMap: {
type: "a",
}
},
{
list: [4,5,6],
dataMap: {
type: "b",
}
},
{
list: [7,8],
dataMap: {
type: "a",
}
},
]
///////////// after converted //////////
{
"a": [1,2,3,7,8],
"b": [4,5,6]
}
您可以使用groupingBy
按type
分組,使用flatMapping
來展平Long
數據列表並收集為單個列表。
Map<String, List<Long>> res =
objectInList
.stream()
.collect(Collectors.groupingBy(
e -> e.getDataMap().get("type"),
Collectors.flatMapping(
e -> e.getListWithLong().stream(),
Collectors.toList())
));
我不確定你為什么需要Map<String, Object> dataMap;
當它應該只有一個值時。 為簡單起見,我已將您的ObjectInList
class 修改為
class ObjectInList {
List<Long> listWithLong;
String type;
}
要獲得分組列表,我們可以這樣做 -
Map<String, List<Long>> grouped =
objectInLists.stream()
.collect(
Collectors.toMap(
ObjectInList::getType,
ObjectInList::getListWithLong,
(oldList, newList) -> {
oldList.addAll(newList);
return oldList;
}));
解釋:
toMap
方法 -
public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction)
toMap
采用keyMapper
,它是ObjectInList::getType
(根據類型進行分組), valueMaper 是ObjectInList::getListWithLong
,因為我們有重復的鍵,我們需要提供一個mergeFunction
作為(oldList, newList) -> {oldList.addAll(newList);return oldList;}
從文檔 -
合並 function,用於解決與同一鍵關聯的值之間的沖突,如提供給 {@link Map#merge(Object, Object, BiFunction)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.