String Compression in Java: Efficient Data Storage Techniques

Photo of author

String compression is a technique to reduce the size of a string by replacing repeating characters with a count of their occurrences. This technique is common in data compression algorithms to reduce memory or disk space.

To perform string compression in Java, you can use three approaches:

  1. Using StringBuilder
  2. Using Regular Expressions
  3. Using a Chart.

string compression

In this article, we will look at the three ways to perform string compression in Java. Read more and learn how to apply string compression in your own Java projects.

See Also: How To Display Time In HTML Using JavaScript?

String Compression in Java: 3 Ways

There are numerous ways to perform string contraction in Java. Then we will be agitating three of the ways to perform string contraction.

Using StringBuilder

Using the StringBuilder class, this is the first approach to perform string contraction in Java. The StringBuilder class provides a set of styles to manipulate strings efficiently. This. As it generates a variable series of characters, the StringBuilder class offers a variation to the string class. The functions of the StringBuilder and StringBuffer classes are the same, as both produce variable sequences of characters as an option to the String Class. Still, syncing is where the StringBuilder class and StringBuffer class diverge. The StringBuilder class doesn’t ensure synchronization.

string builder

As a result, this class is intended to be used in areas where a single thread preliminarily used the StringBuffer as a drop-in relief( as is generally the case). This class is brisk and works snappily on the executions, so using this rather than StringBuffer is doable.

The initial idea behind this approach is to reiterate through the input string, count the number of successive characters, and tack the count to a StringBuilder object.

The basic idea behind this approach is to iterate through the input string, count the number of consecutive characters, and append the count to a StringBuilder object.

The code is as follows:


public static String compressString(String str) {

StringBuilder sb = new StringBuilder();

int count = 1;

char prevChar = str.charAt(0);

for (int i = 1; i < str.length(); i++) {

char currentChar = str.charAt(i);

if (currentChar == prevChar) {

count++;

} else {

sb.append(prevChar);

sb.append(count);

count = 1;

prevChar = currentChar;

}

}

sb.append(prevChar);

sb.append(count);

return sb.toString();

}

We first construct a StringBuilder object in this code to store the compressed string. The first character of the input string is then used as the starting value for the count and prevChar variables. The next step is repeatedly matching each character in the input string to the character before it.

We increase the tally if they are identical. If they are distinct, we update the prevChar variable, append the previous character and its count to the StringBuilder object, and then reset the count to 1. Lastly, we return the compressed string after adding the last character and its count to the StringBuilder object.

Using Regular Expressions in Java

The alternate method is Regular Expressions in Java. Using regular expressions is the alternate system of textbook contraction in Java. String manipulation is made easy with the help of regular expressions.regular expression

A string of letters called a regular expression creates a hunting pattern. You can use this hunt pattern to specify your hunt criteria when looking for information within a document.

A regular expression can be a simple pattern or just a single letter. You can carry out all kinds of textbook hunting and textbook relief tasks using regular expressions. Although Java does not have an erect- in the Regular Expression class, we can use regular expressions by importing Java.util.regex library.

Regex in Java provides us with 3 classes and 1 interface listed below as follows:

Matcher Class

Pattern Class

MatchResult Interface

PatternSyntaxException Class

The code is as follows:


public static String compressString(String str) {

StringBuilder sb = new StringBuilder();

Pattern pattern = Pattern.compile("(.)\\1*");

Matcher matcher = pattern.matcher(str);

while (matcher.find()) {

String group = matcher.group();

sb.append(group.charAt(0));

sb.append(group.length());

}

return sb.toString();

}

Using a chart

Using a Chart is one way to negotiate string contraction in Java.

chart In Java, you can store Chart interface maps variables to values, and the census of each character in the input string using a Chart.

The code is as follows:


public static String compressString(String str) {

Map<Character, Integer> map = new HashMap<>();

StringBuilder sb = new StringBuilder();

for (char c: str.toCharArray()) {

map.put(c, map.getOrDefault(c, 0) + 1);

}

for (Map.Entry<Character, Integer> entry : map.entrySet()) {

sb.append(entry.getKey());

sb.append(entry.getValue());

}

return sb.toString();

}

See Also: Python For Scientific Computing: Everything You Need To Know

FAQs

What is string compression?

String compression is a way to compress a string. When you compress a string, the consecutive duplicate characters of the string are replaced with the number count. For example, when you compress 'aaaibbbbbbpp', it will return as 'a3i1b6p2'.

Which compression format is used by Java?

Java classes support two compression formats that are widely used, i.e., ZIP and GZIP.

What are the 2 types of compressions in Java?

The two types of compressions in Java are Lossy and Lossless. In Lossy compression, your original data will get affected by the compression. But in Lossless, there will be no effect on your original data; it will remove metadata in compression.

Conclusion

To store the count of each character in the input string, we first construct a Chart object in this law. The Chart object’s character count streamlines by repeating through the input string using the put() function.

Using the entrySet() function, we reiterate through the Map object, subjoining each key and value to the StringBuilder object.

We also give the compressed text. Thus this was about string compression in java.

See Also: Python Round() Function: Complete Tutorial

 

Leave a Comment