Skip to content

How can I use java streams to retrieve the value of x names?

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?

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:

private List<NameResponse> names;

NameResponse class:

private String name;

Answer

Something like below assuming you have the appropriate getters:

return customer.getNames()
               .stream()
               .map(NameResponse::getName)
               .collect(Collectors.toList());