Java String: Title Case Format

Java String: Title Case Format

Learn How to Convert Java String to Title Case Format

1. Introduction

In this short tutorial, we'll learn how to convert a Java String to Title Case format.

2. Solution

The approach I used was to lower-case the String, split the String, title-case each word in the array, then join all the words back together as one String.

Here is the code example:

public String titleCase(String line) {
  return Arrays
    // Lower-case the String.
    // Split the String into an Array.
    .stream(line.toLowerCase().split(" "))
    .map(word -> word.isEmpty()
         ? word
         // Title Case the first letter in each word.
         : Character.toTitleCase(word.charAt(0)) + word
         .substring(1))
    // Join the words back together as one String.
    .collect(Collectors.joining(" "));
}

3. Conclusion

In this short tutorial (maybe the shortest on the web), you learned how to convert a Java String to Title Case format.

Did you like it? Why don't you try also...

Split Strings in Java

Split Strings in Java

Learn how to split strings in Java

Java Strings: Testing if a String is Empty or Blank

Java Strings: Testing if a String is Empty or Blank

Learn to test if a String is Empty or Blank

Java Strings: Basic String Methods Part 1

Java Strings: Basic String Methods Part 1

Learn the most common Java String Methods.