SudeepShakya
SudeepShakya

Reputation: 621

Java 8 Streams group by function, setting nested object's variable as key and parent object as value

I assume my question is somewhat clear from the title.

I have two classes : parent A and child B. and want to have return like Map<Integer,A> where key is a field from child B. I have List<A> aList extracted from database. Class Definitions:

public class B {
    Integer id;
    String some;
    String some2;
}

public class A {
    Integer id;
    B someB;
    String name;
}

I was trying like aList.streams.collect(Collectors.groupingBy(A::getSomeB)) but this is not what I want. There is only one to one relationship between parent and child so I don't need Map<Integer,List<A>> as the result

I can do this by looping the aList but if there is a built in Java 8 function, I would like to use it.

Upvotes: 0

Views: 1655

Answers (2)

Eugene
Eugene

Reputation: 120848

You don't even need streams for that, in such a trivial case:

Map<Integer, A> map = new HasMap<>();
aList.forEach(x -> map.merge(x.getSomeB().getId(), x, (oldV, newV) -> throw new AssertionError("must never happen"));

Upvotes: 1

Naman
Naman

Reputation: 31868

You are probably looking out for Collectors.toMap to collect the map of B.id and A as the object

Map<Integer, A> result = aList.stream().collect(
              Collectors.toMap(a -> a.getSomeB().getId(), Function.identity());

Upvotes: 1

Related Questions