I'm practicing Java 8 features and I got to a problem that I couldn't solve:
I have a List of Strings that I need to map into a List of Customers, the List of Strings only has the name of the customers, but Customer Model has other properties:
public class Customer {
private int id{get; set;};
private String name{get; set;};
private String company{get; set;};
}
public static List<Customer> convertList() {
List<Customer> customerList = new ArrayList<Customer>();
List<String> nameList = new ArrayList<String>();
nameList.add("Customer A");
nameList.add("Customer B");
nameList.add("Customer C");
nameList.add("Customer D");
nameList.add("Customer E");
nameList.add("Customer F");
return customerList.stream()
.map()//here I got stuck
.collect(Collectors.toList());
}
What I want to do is to to set the value of the List into the Name property of the List, I tried using a stream and map but couldn't figure how to use it in this scenario.
List<Customer> customerList = nameList.stream().map(name -> {
Customer c = new Customer();
c.setName(name);
c.setId(generateId());
c.setCompany(getCompany(name));
return c;
}).collect(Collectors.toList());
You need to map the nameList
to customerList
so, you should stream on the nameList
and convert it to customerList
not the other way around. Next, you need to figure out how to get the additional information like id, company etc using some external method/service if at all that is required during the map()
operation.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments