4

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;

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

End result must be Iterable<List<?>>. Anything else can be changed/improved. What would be option without ArrayList?
@PutinasPiliponis as I've shown - my code does not use an ArrayList.
Understood :) Question closed. Thanks for answer!
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.