我有一个清单
List<MyObject> list;
我想将其转换为Map<MyObject, List<String>>
我试过
Map<MyObject, List<String>> map = list
.stream()
.collect(Collectors.toMap(item -> item, Collections.emptyList()));
但Java对item->item
:
no instance(s) of type variable(s) T exists so that List<T> conforms to Function<? super T, ? extends U>
感谢帮助
答案 0 :(得分:2)
Collectors.toMap
的第二个参数需要Function
将项目转换为将放置在地图中的值。但是,您提供的Collections.emptyList()
不是Function
。
看起来你想要每个项目的空列表,所以改变
Collections.emptyList()
到
item -> Collections.emptyList()
但是,Collections.emptyList()
会返回不可变的空列表,这可能不是您想要的。
返回一个空列表(不可变)。此列表是可序列化的。
你可能想要
item -> new ArrayList<>()
答案 1 :(得分:1)
您尚未指定每个String
的{{1}}元素来自何处。
如果它们来自每个List<String>
个实例,您可以尝试使用Collectors.groupingBy
和Collectors.mapping
代替MyObject
:
Collectors.toMap
如果每个列表的元素不是属于Map<MyObject, List<String>> map = list.stream()
.collect(Collectors.groupingBy(
item -> item,
Collectors.mapping(item -> item.getSomeStringAttribute(),
Collectors.toList())));
,而是来自其他地方,则可以在方法中封装每个MyObject
元素的获取:
String
Map<MyObject, List<String>> map = list.stream()
.collect(Collectors.groupingBy(
item -> item,
Collectors.mapping(item -> someMethod(item),
Collectors.toList())));
的位置如下:
someMethod
另一方面,如果您只想将带有空列表的地图初始化为每个String someMethod(MyObject item) {
// TODO get/calculate the String from the item
}
实例的值,则不需要流:
MyObject