I'm trying to come up with some nice lambda expressions to build "desiredResult" from "customers" ArrayList. I implemented it in an old ugly way "for" loop. I know there should be nice one-liners, but I can't think of any method - nested arrays come into my way.
Iterable<List<?>> params;
Customer customer1 = new Customer("John", "Nowhere");
Customer customer2 = new Customer("Alma", "Somewhere");
Customer customer3 = new Customer("Nemo", "Here");
Collection<Customer> customers = new ArrayList<>();
customers.add(customer1);
customers.add(customer2);
customers.add(customer3);
Collection<List<?>> desiredResult = new ArrayList<>();
for (Customer customer : customers) {
List<Object> list = new ArrayList<>();
list.add(customer.getName());
list.add(customer.getAddress());
list.add("VIP");
desiredResult.add(list);
}
params = desiredResult;
I'd just use Arrays.asList
for creating the inner lists, which makes the problem much simpler:
Collection<List<?>> desiredResult =
customers.stream()
.map(c -> Arrays.asList(c.getName(), c.getAddress(), "VIP"))
.collect(Collectors.toList());
If you absolutely must have an ArrayList
, just wrap the Arrays.asList
call with it.
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