Skip to content

Case conversion using Stream API in Java 8

There are no direct methods provided by the Java API to convert a string to different cases like Camel Case, Snake Case or Kebab Case. You can accomplish this using Stream API which was introduced in Java 8. Once you convert a string to a stream, you can use the map and collect method to get the case you want.

Camel Case

public static String convert2CamelCase(String str) {
 Matcher matcher = Pattern.compile("[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+").matcher(str);
 List < String > matched = new ArrayList < > ();
 while (matcher.find()) {
  matched.add(matcher.group(0));
 }
 String camelcase = matched.stream()
  .map(x -> x.substring(0, 1).toUpperCase() + x.substring(1).toLowerCase())
  .collect(Collectors.joining());
 return camelcase.substring(0, 1).toLowerCase() + camelcase.substring(1);
}

Snake Case

public static String convert2SnakeCase(String input) {
 Matcher matcher = Pattern.compile("[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+").matcher(input);
 List < String > matched = new ArrayList < > ();
 while (matcher.find()) {
  matched.add(matcher.group(0));
 }
 return matched.stream()
  .map(String::toLowerCase)
  .collect(Collectors.joining("_"));
}

Kebab Case

public static String convert2KebabCase(String input) {
 Matcher matcher = Pattern.compile("[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+").matcher(input);
 List < String > matched = new ArrayList < > ();
 while (matcher.find()) {
  matched.add(matcher.group(0));
 }
 return matched.stream()
  .map(String::toLowerCase)
  .collect(Collectors.joining("-"));
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.