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);
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);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With