本文介绍了使用Streams API和Collectors.toMap()使用对象引用作为键构造Map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个 Map< Item,List< String>> ,即使用 Item 引用作为键,使用一些任意 List< String> 作为值。我尝试了以下内容,但它会在IntelliJ中显示类型推断错误(但是,它仍然会编译);

I want to construct a Map<Item, List<String>>, i.e. using the Item reference as key, with some arbitrary List<String> as value. I've attempted the following, but it will show type inference error in IntelliJ (however, it will still compile);

List<Item> items = getItems(...);
Map<Item, List<String>> itemMap = items.stream().collect(Collectors.toMap(i->i, new ArrayList<>()));

然后,我通过 get(),它只返回自己的实例;

I then created a workaround through a helper method in Item, get(), which just returns its own instance;

public Item get(){ return this; }

然后尝试使用相同的方法,使用 get()访问参考的方法:

Then tried the same approach, using the get() method to access the reference:

List<Item> items = getItems(...);
Map<Item, List<String>> itemMap = items.stream().collect(Collectors.toMap(Item::get, new ArrayList<>()));

现在它至少会编译,但感觉不对

Now it will at least compile, but it feels wrong.

如何以正确的方式解决这个问题?

How would one actually go around solving this in a proper manner?

编辑:问题现在完全不同从最初发布的内容,反映在收到的评论中。

Question is now radically different from what was originally posted, reflected by the comments received.

推荐答案

实现它的正确方法是包含类型参数,如所以;

The proper way of achieving it was to include a type argument like so;

List<Item> items = getItems(...);
Map<Item, List<String>> itemMap = items.stream().collect(Collectors.toMap(Function.<Item>identity(), v -> new ArrayList<>()));

另外;

List<Item> items = getItems(...);
Map<Item, List<String>> itemMap = items.stream().collect(Collectors.toMap(v -> v, v -> new ArrayList<String>()));

这篇关于使用Streams API和Collectors.toMap()使用对象引用作为键构造Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:25