如何转换列表<;对象>;映射<;K、 V>;使用java流
我想将如何转换列表<;对象>;映射<;K、 V>;使用java流,java,java-8,java-stream,Java,Java 8,Java Stream,我想将列表转换为地图 您可以使用groupingBy按type分组,并使用flatMapping展平长数据列表并作为单个列表收集 Map<String, List<Long>> res = objectInList .stream() .collect(Collectors.groupingBy( e -> e.getDataMap().get("type"),
列表
转换为地图
您可以使用
groupingBy
按type
分组,并使用flatMapping
展平长
数据列表并作为单个列表收集
Map<String, List<Long>> res =
objectInList
.stream()
.collect(Collectors.groupingBy(
e -> e.getDataMap().get("type"),
Collectors.flatMapping(
e -> e.getListWithLong().stream(),
Collectors.toList())
));
Map res=
客观主义者
.stream()
.collect(收集器.groupingBy(
e->e.getDataMap().get(“类型”),
平面映射(
e->e.getListWithLong().stream(),
Collectors.toList())
));
您可以使用groupingBy
按类型进行分组
和flatMapping
展平长
数据列表,并作为单个列表进行收集
Map<String, List<Long>> res =
objectInList
.stream()
.collect(Collectors.groupingBy(
e -> e.getDataMap().get("type"),
Collectors.flatMapping(
e -> e.getListWithLong().stream(),
Collectors.toList())
));
Map res=
客观主义者
.stream()
.collect(收集器.groupingBy(
e->e.getDataMap().get(“类型”),
平面映射(
e->e.getListWithLong().stream(),
Collectors.toList())
));
我不知道你为什么需要地图数据地图代码>当它应该只有一个值时。为简单起见,我将您的ObjectInList
类修改为
class ObjectInList {
List<Long> listWithLong;
String type;
}
toMap
使用keyMapper
,它是ObjectInList::getType
(根据类型进行分组),valueMaper是ObjectInList::getListWithLong
,由于我们有重复的键,我们需要提供mergeFunction
作为(oldList,newList)->{oldList addAll(newList);返回oldList;}
从文件-
合并函数,用于解决关联值之间的冲突
使用提供给{@link Map#merge(Object,Object,
双功能
我不知道为什么您需要Map dataMap;
,而它应该只有一个值。为简单起见,我将您的ObjectInList
类修改为
class ObjectInList {
List<Long> listWithLong;
String type;
}
toMap
使用keyMapper
,它是ObjectInList::getType
(根据类型进行分组),valueMaper是ObjectInList::getListWithLong
,由于我们有重复的键,我们需要提供mergeFunction
作为(oldList,newList)->{oldList addAll(newList);返回oldList;}
从文件-
合并函数,用于解决关联值之间的冲突
使用提供给{@link Map#merge(Object,Object,
双功能
每个映射都包含一个条目?我认为您的模型应该是DateType数据映射;
和class DateType{private String type}
并且每个映射都包含一个条目?我认为您的模型应该是DateType数据映射;
和class DateType{private String type}
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;
}));
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)