Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using stream API to set strings all lowercase but capitalize first letter

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
like image 546
Devin Avatar asked Dec 11 '18 23:12

Devin


People also ask

How do I change the first letter of a string to lowercase?

Or using a char array String input = "SomeInputString"; char c[] = input. toCharArray(); c[0] = Character. toLowerCase(c[0]); String output = new String(c);

How do you capitalize the first character of each word in a string?

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.

How do you make the first letter capital in C++?

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++.


2 Answers

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));
  1. note that I've changed the comparator, which is essentially the idiomatic approach to do it.
  2. I've added a map operation after sorting to uppercase the first letter.
like image 109
Ousmane D. Avatar answered Sep 18 '22 22:09

Ousmane D.


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);
like image 33
Andrew Tobilko Avatar answered Sep 19 '22 22:09

Andrew Tobilko