Search code examples
javajava-streamcollectors

Trasform a Tuple to List of Objects with Java Streams


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.


Solution

  • You can follow these steps:

    1. group tuple List by key
    2. map the to the object son
    3. collect to list
    4. convert map to a list of mothers
    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();