Java Squeeze Repetition Characters in a String using Apache Commons Lang

Tags: CharSetUtils Apache Commons Apache Commons Lang String

In this Java tutorial we learn how to squeeze any repetition characters in a given String using the CharSetUtils class of Apache Commons Lang library.

How to add Apache Commons Lang 3 library to your Java project

To use the Apache Commons Lang 3 library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'org.apache.commons:commons-lang3:3.12.0'

To use the Apache Commons Lang 3 library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.12.0</version>
</dependency>

To have more information about the Apache Commons Lang 3 library you can visit the library home page at commons.apache.org/proper/commons-lang/

How to squeeze repetition Characters in a String in Java

The Apache Commons Lang library provides the method CharSetUtils.squeeze() to delete duplicate characters and keep only one character if any repetition is found in a given String value. You can learn how to use the CharSetUtils.squeeze() method via example code below.

SqueezeCharactersPresentInString.java

import org.apache.commons.lang3.CharSetUtils;

public class SqueezeCharactersPresentInString {
    public static void main(String... args) {
        String stringToTest = "Simplllle Solutioon";

        String result1 = CharSetUtils.squeeze(stringToTest, "k-o");
        String result2 = CharSetUtils.squeeze(stringToTest, "x-z");
        String result3 = CharSetUtils.squeeze(stringToTest, "klmno");
        String result4 = CharSetUtils.squeeze(stringToTest, "xyz");
        String result5 = CharSetUtils.squeeze(stringToTest, "k", "l", "m", "n", "o");
        String result6 = CharSetUtils.squeeze(stringToTest, "x", "y", "z");

        System.out.println("Squeeze \"k-o\" result: " + result1);
        System.out.println("Squeeze \"x-z\" result: " + result2);
        System.out.println("Squeeze \"klmno\" result: " + result3);
        System.out.println("Squeeze \"xyz\" result: " + result4);
        System.out.println("Squeeze \"k\", \"l\", \"m\", \"n\", \"o\" result: " + result5);
        System.out.println("Squeeze \"x\", \"y\", \"z\" result: " + result6);
    }
}
The output is:
Squeeze "k-o" result: Simple Solution
Squeeze "x-z" result: Simplllle Solutioon
Squeeze "klmno" result: Simple Solution
Squeeze "xyz" result: Simplllle Solutioon
Squeeze "k", "l", "m", "n", "o" result: Simple Solution
Squeeze "x", "y", "z" result: Simplllle Solutioon

Happy Coding 😊