Lambda expressions and nested arrays

I'm trying to come up with some nice lambda expressions to build a "wishResult" from the "clients" of an ArrayList. I implemented it in an old ugly way for a loop. I know that there should be good one-liners, but I cannot come up with any method - nested arrays will come into my head.

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;
+4
source share
2 answers

I would use Arrays.asListto create internal lists, which makes the problem much easier:

Collection<List<?>> desiredResult = 
    customers.stream()
             .map(c -> Arrays.asList(c.getName(), c.getAddress(), "VIP"))
             .collect(Collectors.toList());

If you absolutely must have ArrayList, just wrap it in a call Arrays.asList.

+4
source

Here is a suggestion:

Collection<List<?>> desiredResult = customers.stream()
         .map(MyClass::customerToList)
         .collect(toList());

- :

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;
}
+3

Source: https://habr.com/ru/post/1682957/


All Articles