我想使用Java 8的流和lambdas将对象列表转换为Map。

这是我在Java 7及以下版本中编写它的方式。

private Map<String, Choice> nameMap(List<Choice> choices) {
        final Map<String, Choice> hashMap = new HashMap<>();
        for (final Choice choice : choices) {
            hashMap.put(choice.getName(), choice);
        }
        return hashMap;
}

我可以很容易地完成这一点使用Java 8和番石榴,但我想知道如何做到这一点没有番石榴。

番石榴:

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, new Function<Choice, String>() {

        @Override
        public String apply(final Choice input) {
            return input.getName();
        }
    });
}

番石榴和Java 8 lambdas。

private Map<String, Choice> nameMap(List<Choice> choices) {
    return Maps.uniqueIndex(choices, Choice::getName);
}

当前回答

我试图这样做,并发现,使用上面的答案,当使用Functions.identity()的键到地图,然后我有使用本地方法这样::localMethodName实际工作的问题,因为键入问题。

在这种情况下,Functions.identity()实际上对类型做了一些事情,因此该方法只能通过返回Object并接受Object的参数来工作

为了解决这个问题,我最终放弃了Functions.identity(),转而使用s->s。

所以我的代码,在我的例子中列出一个目录内的所有目录,对于每个目录,使用目录名作为映射的键,然后调用一个具有目录名的方法并返回一个项目的集合,如下所示:

Map<String, Collection<ItemType>> items = Arrays.stream(itemFilesDir.listFiles(File::isDirectory))
.map(File::getName)
.collect(Collectors.toMap(s->s, this::retrieveBrandItems));

其他回答

列出的大多数答案,当列表有重复项时,会漏掉一个情况。在这种情况下,答案会抛出IllegalStateException。参考下面的代码来处理列表副本:

public Map<String, Choice> convertListToMap(List<Choice> choices) {
    return choices.stream()
        .collect(Collectors.toMap(Choice::getName, choice -> choice,
            (oldValue, newValue) -> newValue));
  }

这里是另一个,以防你不想使用collections . tomap ()

Map<String, Choice> result =
   choices.stream().collect(HashMap<String, Choice>::new, 
                           (m, c) -> m.put(c.getName(), c),
                           (m, u) -> {});

使用getName()作为键,Choice本身作为映射的值:

Map<String, Choice> result =
    choices.stream().collect(Collectors.toMap(Choice::getName, c -> c));

你可以使用IntStream创建一个索引流,然后将它们转换为Map:

Map<Integer,Item> map = 
IntStream.range(0,items.size())
         .boxed()
         .collect(Collectors.toMap (i -> i, i -> items.get(i)));
Map<String,Choice> map=list.stream().collect(Collectors.toMap(Choice::getName, s->s));

甚至对我来说,

Map<String,Choice> map=  list1.stream().collect(()-> new HashMap<String,Choice>(), 
            (r,s) -> r.put(s.getString(),s),(r,s) -> r.putAll(s));