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
Or using a char array String input = "SomeInputString"; char c[] = input. toCharArray(); c[0] = Character. toLowerCase(c[0]); String output = new String(c);
To capitalize the first character of a string, We can use the charAt() to separate the first character and then use the toUpperCase() function to capitalize it. Now, we would get the remaining characters of the string using the slice() function.
Using toupper() function The standard solution to convert a lowercase letter to uppercase is using the toupper() function from <cctype> header. The idea is to extract the first letter from the given string, and convert it to uppercase. This works in-place, since strings are mutable in C++.
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));
map
operation after sorting to uppercase the first letter.list.stream()
.map(s -> s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase())
.sorted(Comparator.comparingInt(String::length))
.forEach(System.out::println);
For readability, the line performing capitalisation should be moved into a method,
public class StringUtils {
public static String capitalise(String s) {
return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
}
so you can refer to it via an eloquent method reference:
list.stream()
.map(StringUtils::capitalise)
.sorted(Comparator.comparingInt(String::length))
.forEach(System.out::println);
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