4

Given list of customers, I need to create another list with first names of customers in upper case. This is the code in java-

List<String> getFirstNames(List<Customer> customers)
{
    List<String> firstNames = new ArrayList<>();
    for(Customer customer: customers) {
        firstNames.add(StringUtils.uppercase(customer.getFirstName());
    }
    return firstNames;
}

How do I write this method using lambda in java8. I could use streams in this way, to convert to list-

customers.stream().map(Customer::getFirstName).collect(Collectors.toList());

But, how can I convert firstName to upper case, using this?

3
  • 6
    With method references customers.stream().map(Customer::getFirstName).map(StringUtils::uppercase).collect(toList()); Commented Jun 12, 2015 at 2:14
  • 1
    Any reason to use StringUtils.uppercase(customer.getFirstName()) instead of simply customer.getFirstName().toUpperCase()? Commented Jun 12, 2015 at 13:46
  • @SotiriosDelimanolis Shouldn't we prefer to do it in one line as in the answer instead of doing it in 2 iterations? Commented Apr 5, 2018 at 16:03

2 Answers 2

4

Easiest way is to write your own lambda expression that does the conversion to uppercase for you:

 List<String> firstNames = customers.stream()
                         .map(customer->StringUtils.uppercase(customer.getFirstName()))
                        .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

1

Even in your code you are taking the customer name and then doing toUpperCase.

      List<String> firstNames = customers.stream()
                    .map(customer-> customer.getFirstName())
                    .map(firstName -> StringUtils.uppercase(firstName))
                    .collect(Collectors.toList())

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.