Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expressions and nested arrays

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;
like image 529
lapkritinis Avatar asked Mar 08 '23 10:03

lapkritinis


1 Answers

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.

like image 75
Mureinik Avatar answered Mar 15 '23 13:03

Mureinik