Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream .map capitalize first letter only

Tags:

java

string

I'm trying to sort my list alphabetically and also capitalize the first letter of each name.

When I do toUpperCase, it capitalizes every letter. If I were to print it without using .map, I would do (topNames2017.substring(0, 1).toUpperCase() + topNames2017.substring(1)) which works fine, but I don't know how to apply it here

List<String> topNames2017 = Arrays.asList(
            "Amelia",
            "Olivia",
            "emily",
            "Isla",
            "Ava",
            "oliver",
            "Jack",
            "Charlie",
            "harry",
            "Jacob"
    );


      topNames2017
            .stream()
            .map(String::toUpperCase)
            .sorted()
            .forEach(System.out::println);
like image 876
Workkkkk Avatar asked Nov 30 '22 22:11

Workkkkk


2 Answers

You'll need to use a lambda to get your current attempt to work, example:

.map(name -> name.substring(0, 1).toUpperCase() + name.substring(1))

The name identifier above represents the current string passed to the map operation.

Alternatively, it can also be done like this:

.map(name -> Character.toUpperCase(name.charAt(0)) + name.substring(1))

If you want to maintain the use of method reference then you can define your own function like this:

static String capitaliseFirstLetter(String name){
      return name.substring(0, 1).toUpperCase() + name.substring(1);
}

Now, you can do:

topNames2017.stream()
            .map(Main::capitaliseFirstLetter) // replace Main with the class containing the capitaliseFirstLetter method
            .sorted()
            .forEach(System.out::println);
like image 82
Ousmane D. Avatar answered Dec 05 '22 05:12

Ousmane D.


If you can use Apache Commons, I would suggest WordUtils.capitalize(String) like

topNames2017.stream()
        .map(WordUtils::capitalize)
        .sorted()
        .forEachOrdered(System.out::println);

If you can't use that, then you might do something like

topNames2017.stream()
        .map(x -> x.substring(0, 1).toUpperCase() + x.substring(1))
        .sorted()
        .forEachOrdered(System.out::println);

In either case, if you are sorting, make sure to use forEachOrdered.

like image 31
Elliott Frisch Avatar answered Dec 05 '22 04:12

Elliott Frisch