I can use the below snippet to retrieve the name if there is 1 entry in the list by retrieving element 0 in the list, however, each NameResponse
can have several names (e.g. a first name, a middle name and a surname). How can I retrieve x names associated with one customer? There could be 20 names for argument’s sake. I would like to implement using a stream since I am using Java 8, but I am unsure how to implement this. Any suggestions?
JavaScript
x
private List<String> getNames(Customer customer) {
List<NameResponse> nameResponses = new ArrayList<>();
NameResponse nameResponse = new NameResponse();
nameResponse.setName("Test Name");
nameResponses.add(nameResponse);
customer.setNames(nameResponses);
return List.of(customer.getNames().get(0).getName());
}
Customer class:
JavaScript
private List<NameResponse> names;
NameResponse class:
JavaScript
private String name;
Advertisement
Answer
Something like below assuming you have the appropriate getters:
JavaScript
return customer.getNames()
.stream()
.map(NameResponse::getName)
.collect(Collectors.toList());