Java 将贴图转换为贴图

Java 将贴图转换为贴图,java,java-8,java-stream,Java,Java 8,Java Stream,使用java8和流api 只有一个MyObject,我想转换 Map<Long, MyObject> 到 列表中有一个元素的位置?您只需获取条目集流,并将toMap收集器与Collections.singletonList结合使用,它创建一个不可变列表,以从原始映射创建新值 Map<Long, MyObject> yourMap = whateverYouImplementedHere; Map<Long, List<MyObject>> li

使用java8和流api

只有一个MyObject,我想转换

Map<Long, MyObject> 


列表中有一个元素的位置?

您只需获取条目集流,并将toMap收集器与Collections.singletonList结合使用,它创建一个不可变列表,以从原始映射创建新值

Map<Long, MyObject> yourMap = whateverYouImplementedHere;
Map<Long, List<MyObject>> listMap = new HashMap<>();

for (Entry<Long, MyObject> entry : yourMap.entrySet()){

    listMap.put(entry.getKey(), new ArrayList<MyObject>(Arrays.asList(entry.getValue()));
}
Map<Long, List<MyObject>> transformedMap = 
    map.entrySet()
       .stream()
       .collect(toMap(Map.Entry::getKey, 
                      e -> Collections.singletonList(e.getValue())));

如果你只有一把钥匙,为什么要用地图?而不是一个集合?@ManuelS一个值,不是一个键。只有一个MyObject…为什么要使用List?我建议你看看Guava MultiMap。它是一个谷歌图书馆,提供了一个非常好的数据结构方法。看看post的例子。@SarithaG有很多原因。你需要知道我为之制作的api,或者我的deak上的所有业务需求来回答这个问题吗?这将解决OP的一般问题,尽管其他数据结构要好得多。这没有使用java 8流特性。这个lambda表达式对于OP来说可能有点过头了,因为他似乎是个初学者,但答案仍然是正确的+1@RoelStrolenbergOP有一个金爪哇徽章,我不认为他是绿色的。
Map<Long, List<MyObject>> newMap = oldMap.entrySet().stream()
                 .collect(Collectors.toMap(
                            Entry::getKey, 
                            e -> new ArrayList<>(Arrays.asList(e.getValue()))));
                            e -> Collections.nCopies(1, e.getValue())));
Map<Long, List<MyObject>> transformedMap = 
    map.entrySet()
       .stream()
       .collect(toMap(Map.Entry::getKey, 
                      e -> Collections.singletonList(e.getValue())));