emoleumassi
emoleumassi

Reputation: 5159

Java8: Map list of objects by key

Map<A, List<B>> xFunction() {    
    Map<A, List<B>> mapList = new HashMap<>();
    List<A> aList = x.getAList();
    for (A a : aList) {
        List<B> bList = getBList(a.getId());
        mapList.put(a, bList);
    }
    return mapList;
}

How to convert this in java 8 with collect and grouping by or mapping?

I try with something like:

x.getAList
.stream()
.map(a -> getBList(a.getId)) //return a list of B
.collect(Collectors.groupingBy (...) )

Cheers

Upvotes: 2

Views: 777

Answers (2)

Vlad Bochenin
Vlad Bochenin

Reputation: 3082

@Eran was first but to reproduce behavior you should use toMap collector with mergeFunction for duplicates by a.getId() because by default Java will throw IllegalStateException for entries with the same key:

x.getAList()
    .stream()
    .collect(Collectors.toMap(Function.identity(), a -> getBList(a.getId())), (u, u2) -> u2);

Upvotes: 3

Eran
Eran

Reputation: 394156

You need Collectors.toMap:

Map<A, List<B>> map =
    x.getAList()
     .stream()
     .collect(Collectors.toMap (Function.identity(), a -> getBList(a.getId())));

Upvotes: 6

Related Questions