如何转换列表<;对象>;映射<;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)