Given a List<Tuple>
from a class shaped like this:
class Tuple {
String key,
String key_key,
String key_value
}
and given two classes:
class Mother {
String key,
List<Son> sons
}
class Son {
String key,
String value
}
which way I can map the tuples into the Mother class, for example:
k1, kk1, kv1
k1, kk1, kv2
k2, kk3, kv3
would result in:
k1 -> [[kk1, kv1], [kk1, kv2]]
k2 -> [[kk3, kv3]]
I'm completely confused between flatmap and collectors.
You can follow these steps:
Map<String, List<Son>> mapWithSons = tupleList.stream()
.collect(Collectors.groupingBy(t -> t.key, //1
Collectors.mapping(t -> new Son(t.key_key, t.key_value), //2
Collectors.toList()))); //3
List<Mother> motherList = mapWithSons.entrySet()
.stream()
.map(entry -> new Mother(entry.getKey(), entry.getValue())) //4
.toList();