Java 8 List <T> to map <K, V>

I want to convert the List of objects to Map, where the Map and the value are as attributes inside the Object in List.

Here is a fragment of Java 7 of such a conversion:

private Map<String, Child> getChildren(List<Family> families  ) {
        Map<String, Child> convertedMap = new HashMap<String, Child>();

        for (Family family : families) {
            convertedMap.put(family.getId(), family.getParent().getChild());
        }
        return convertedMap;
    }
+4
source share
2 answers

It should be something like ...

Map<String, Child> m = families.stream()
    .collect(Collectors.toMap(Family::getId, f -> f.getParent().getChild()));
+10
source

(+1), , OP Java 7. , . , , . , OP, Family Family .

( , ):

Map<String, Child> getChildren(List<Family> families) {
    return families.stream()
        .collect(Collectors.toMap(Family::getId, f -> f.getParent().getChild()));
}

Collectors.toMap IllegalStateException, . , , , , . Collectors.toMap(keyMapper, valueMapper) , , map keyper .

, - - . - : Collectors.toMap(keyMapper, valueMapper, mergeFunction). , . , ( Java 7), :

Map<String, Child> getChildren(List<Family> families) {
    return families.stream()
        .collect(Collectors.toMap(Family::getId, f -> f.getParent().getChild(),
                                                 (child1, child2) -> child2));
}

, . , ​​ . , groupingBy, . , ID. , , , . :

Map<String, List<Child>> getChildren(List<Family> families) {
    return families.stream()
        .collect(Collectors.groupingBy(Family::getId,
                    Collectors.mapping(f -> f.getParent().getChild(),
                        Collectors.toList())));
}

, Map<String, Child> Map<String, List<Child>>.

+8

All Articles