There is a List A with property Developer. Developer schema likes that:
@Getter @Setter public class Developer { private String name; private int age; public Developer(String name, int age) { this.name = name; this.age = age; } public Developer name(String name) { this.name = name; return this; } public Developer name(int age) { this.age = age; return this; } }
List A with properties:
List<Developer> A = ImmutableList.of(new Developer("Ivan", 25), new Developer("Curry", 28));
It is demanded to convert List A to List B which with property ProductManager and the properties is same as the ones of List A.
@Getter @Setter public class ProductManager { private String name; private int age; public ProductManager(String name, int age) { this.name = name; this.age = age; } public ProductManager name(String name) { this.name = name; return this; } public ProductManager name(int age) { this.age = age; return this; } }
In the old days, we would write codes like:
public List<ProductManager> convert() { List<ProductManager> pros = new ArrayList<>(); for (Developer dev: A) { ProductManager manager = new ProductManager(); manager.setName(dev.getName()); manager.setAge(dev.getAge()); pros.add(manager); } return pros; }
How could we write the above in a more elegant and brief manner with Java 8?
Another approach to copying elements is using the addAll method: List<Integer> copy = new ArrayList<>(); copy. addAll(list); It's important to keep in mind whenever using this method that, as with the constructor, the contents of both lists will reference the same objects.
Thus, converting the whole list into a list of lists. Use another list 'res' and a for a loop. Using split() method of Python we extract each element from the list in the form of the list itself and append it to 'res'. Finally, return 'res'.
In Java 8, we have the ability to convert an object to another type using a map() method of Stream object with a lambda expression. The map() method is an intermediate operation in a stream object, so we need a terminal method to complete the stream.
you will have to use something like below :
List<ProductManager> B = A.stream() .map(developer -> new ProductManager(developer.getName(), developer.getAge())) .collect(Collectors.toList());
// for large # of properties assuming the attributes have similar names //other wise with different names refer this
List<ProductManager> B = A.stream().map(developer -> { ProductManager productManager = new ProductManager(); try { PropertyUtils.copyProperties(productManager, developer); } catch (Exception ex) { ex.printStackTrace(); } return productManager; }).collect(Collectors.toList()); B.forEach(System.out::println);
Probably, like this:
List<ProductManager> B = A.stream() .map(developer -> new ProductManager(developer.name, developer.age)) .collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With