简体   繁体   中英

I have a nested object structure. I want to create a list of object picking attributes from the nested object using streams in Java

// input
public class A {
   int a1;
   String a2;
   int a3;
   String a4;
   Object B;
}

public class B {
   List<Object> C;
}

public class C {
   int c1;
   Date d;
   List<E> e;
}

public class E {
   int e1;
   int e2;
}

---------------------------------------

// output
public class H {
   int a1;
   String a2;
   int a3;
   String a4;
   int c1;
   Date d;
   int e1;
   int e2;
}

Above (Object A) is the structure of the nested object I have. I want to create a list of Object H, picking attributes as mentioned. I'm able to do this using traditional nested for loops but looking for something more optimal and cleaner preferably using streams.

The input to the function would be List<A> and output should be List<H> .

Recommend taking a look at some guides or examples for Java stream such as https://mkyong.com/java8/java-8-streams-map-examples/ or https://www.baeldung.com/java-8-streams .

You can create a converter function and use Stream::map().

public List<H> convert(List<A> listOfA) {
  return listOfA.stream().map(this::convert).collect(Collectors.toList());
}

public H convert(A a) {
  // Create a new H.
  // Extract attributes from A and set in H.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM