Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple operations in map method using streams in Java8

Tags:

lambda

java-8

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?

like image 523
Teja Avatar asked Sep 06 '25 15:09

Teja


1 Answers

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());
like image 99
dkatzel Avatar answered Sep 08 '25 04:09

dkatzel