Reputation: 2814
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;
Upvotes: 4
Views: 440
Reputation: 311088
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.
Upvotes: 4
Reputation: 328598
Here is a suggestion:
Collection<List<?>> desiredResult = customers.stream()
.map(MyClass::customerToList)
.collect(toList());
I have extracted the list building into a separate method for better readability - the corresponding method would look like this:
private static List<Object> customerToList(Customer c) {
List<Object> list = new ArrayList<>();
list.add(c.getName());
list.add(c.getAddress());
list.add("VIP");
return list;
}
Upvotes: 3