我想使用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);
}

当前回答

根据collector文档,它很简单:

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

其他回答

如果相同键名的每个新值都必须重写:

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

如果所有的选项都必须组合在一个列表中作为一个名称:

public Map < String, Choice > convertListToMap(List < Choice > choices) {
    return choices.stream().collect(Collectors.groupingBy(Choice::getName));
}

这可以通过两种方式来实现。让person作为我们将要用来演示它的类。

public class Person {

    private String name;
    private int age;

    public String getAge() {
        return age;
    }
}

让persons作为要转换到地图的person列表

1.在列表中使用简单的foreach和Lambda表达式

Map<Integer,List<Person>> mapPersons = new HashMap<>();
persons.forEach(p->mapPersons.put(p.getAge(),p));

2.使用在给定列表中定义的流上的收集器。

 Map<Integer,List<Person>> mapPersons = 
           persons.stream().collect(Collectors.groupingBy(Person::getAge));

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

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

可以使用kotlin-stdlib作为番石榴的替代品

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

又多了一个简单的选择

Map<String,Choice> map = new HashMap<>();
choices.forEach(e->map.put(e.getName(),e));