Devin :
I have a List<String>
and through only using the stream API I was settings all strings to lowercase, sorting them from smallest string to largest and printing them. The issue I'm having is capitalizing the first letter of the string.
Is that something I do through .stream().map()
?
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("SOmE", "StriNgs", "fRom", "mE", "To", "yOU");
list.stream()
.map(n -> n.toLowerCase())
.sorted((a, b) -> a.length() - b.length())
.forEach(n -> System.out.println(n));;
}
}
Output:
me
to
you
some
from
strings
Desired output:
Me
To
You
Some
From
Strings
Ousmane D. :
Something like this should suffice:
list.stream()
.map(n -> n.toLowerCase())
.sorted(Comparator.comparingInt(String::length))
.map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1))
.forEachOrdered(n -> System.out.println(n));
- note that I've changed the comparator, which is essentially the idiomatic approach to do it.
- I've added a
map
operation after sorting to uppercase the first letter.