Search code examples
javacollectionsjava-8java-stream

How to group flat structure object into hierarchical model based on few matching properties and nested objects as collection - Java Streams


I have list of flat structure objects of type Model_1 with properties mentioned below it.

How can I convert them into grouped nested objects(Of type Model_2 below) based on few matching properties.

enter image description here

Apologies for putting details into an image, I could only find it as simple way to explain the problem easily.


Solution

  • Some container/wrapper class may be needed to represent a key with A, B (e.g., simple list or a record in Java 16+), then common grouping/mapping may be applied to build a map which entries can be converted then into a list of Model_2:

    record MyKey(A a, B b) {}
    
    public static List<Model_2> convert(List<Model_1> list) {
        return list.stream()
            .collect(Collectors.groupingBy(
                m1 -> new MyKey(m1.getA(), m1.getB()),
                Collectors.mapping(
                    m1 -> new SubModel(m1.getC(), m1.getD()),
                    Collectors.toList()
                )
            )) // Map<MyKey, List<SubModel>>
            .entrySet()
            .stream()
            .map(e -> new Model2(e.getKey().a(), e.getKey().b(), e.getValue()))
            .collect(Collectors.toList());
    }