Two ways to achieve this -
Using Apache Commons Library
public static String convertToTileCase(String text) {
return WordUtils.capitalizeFully(text);
}
Custom function
private final static String WORD_SEPARATOR = " ";
public static String changeToTitleCaseCustom(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return Arrays.stream(text.split(WORD_SEPARATOR))
.map(word -> word.isEmpty()
? word
: Character.toTitleCase(word.charAt(0)) + word.substring(1).toLowerCase()
)
.collect(Collectors.joining(WORD_SEPARATOR));
}
Calling above custom function -
System.out.println(
changeToTitleCaseCustom("JEAN-CLAUDE DUSSE") + "\n" +
changeToTitleCaseCustom("sinéad o'connor") + "\n" +
changeToTitleCaseCustom("émile zola") + "\n" +
changeToTitleCaseCustom("O'mALLey") + "\n");
Output -
Jean-claude Dusse
Sinéad O'connor
Émile Zola
O'malley