Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Tuesday, November 9, 2021

Java 8 Streams - Removing A Character From String

1. Overview

In this tutorial, We'll learn how to remove the specific character from the given string in java with java 8 streams api.

This problem can be solved in many ways but we will solve in most used 4 ways.
Java 8 Streams - Removing A Character From String


2. Removing A Character From String Using replaceAll()


First, we use the replaceAll() method from String class. This method takes the regex and string to be replaced with the regex matched substring.

Look at the following example.
package com.javaprogramto.programs.strings.remove.character;

public class StringRemoveCharacterExample {

	public static void main(String[] args) {

		String input = "hello 0world 00";

		String output = input.replaceAll("0", "");
		
		System.out.println("Input string 1 : "+input);
		System.out.println("Output string after removing the + symbol : "+output);
	}
}

Output:
Input string 1 : hello 0world 00
Output string after removing the + symbol : hello world 
The above code does not work for the special characters. If input string contains any one of these characters(<, (, [, {, \, ^, -, =, $, !, |, ], }, ), ?, *, +, ., >) then it will throw PatternSyntaxException.
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 0
+
^
	at java.base/java.util.regex.Pattern.error(Pattern.java:2029)
	at java.base/java.util.regex.Pattern.sequence(Pattern.java:2204)
	at java.base/java.util.regex.Pattern.expr(Pattern.java:2070)
	at java.base/java.util.regex.Pattern.compile(Pattern.java:1784)
	at java.base/java.util.regex.Pattern.<init>(Pattern.java:1431)
	at java.base/java.util.regex.Pattern.compile(Pattern.java:1070)
	at java.base/java.lang.String.replaceAll(String.java:2141)
	at com.javaprogramto.programs.strings.remove.character.StringRemoveCharacterExample.main(StringRemoveCharacterExample.java:9)

To handle the special escape characters, we need to pass the regex pattern to Pattern.quote() method. This method converts into the literal pattern matching string.
package com.javaprogramto.programs.strings.remove.character;

import java.util.regex.Pattern;

public class StringRemoveCharacterExample2 {

	public static void main(String[] args) {

		String input = "hello +world ++";

		String output = input.replaceAll(Pattern.quote("+"), "");
		
		System.out.println("Input string 1 : "+input);
		System.out.println("Output string after removing the + symbol : "+output);
	}
}


Output:
Input string 1 : hello +world ++
Output string after removing the + symbol : hello world 

3. Removing A Character From String Using StringBuilder


Next, let us look at the another approach to solve this problem using StringBuilder.

Here, we need to iterate the string character over the for loop and compare each of them with the character to remove. If the current character is not matched to the removal character then add the current char to the StringBuilder using append() method.


The example code is below.
package com.javaprogramto.programs.strings.remove.character;

public class StringRemoveCharacterExample3 {

	public static void main(String[] args) {

		String input = "hello +world ++";
		char removalCh = '+';

		char[] chars = input.toCharArray();

		StringBuilder builder = new StringBuilder();

		for (char ch : chars) {

			if (ch != removalCh) {
				builder.append(ch);
			}

		}

		System.out.println("Input string 1 : " + input);
		System.out.println("Output string after removing the + symbol : " + builder.toString());
	}
}
Output:
Input string 1 : hello +world ++
Output string after removing the + symbol : hello world 

This program works for all escape characters also without any runtime exceptions.

4. Java 8 Streams - Removing A Character From String


Next solution is in java 8 using stream api methods.

Java 8 example:
package com.javaprogramto.programs.strings.remove.character;

import java.util.stream.Collectors;

public class StringRemoveCharacterExample4 {

	public static void main(String[] args) {

		String input = "hello +world ++";
		char removalCh = '+';

		String output = input.chars()
							.filter(ch -> ch != removalCh)
							.mapToObj(ch -> String.valueOf(ch))
							.collect(Collectors.joining());

		System.out.println("Input string 1 : " + input);
		System.out.println("Output string after removing the + symbol : " + output);
	}
}

If you want to remove the surrogate pairs then use codepoints() instead of chars() method and compare the codepoints rather than character.

5. Java Removing A Character From String Using Apache Commons


As of now, all examples shown are based on the java api but apache commons lang api has builtin utility class StringUtils.

Use StringUtils.remove() method to remove the given character from the string.

Example:
package com.javaprogramto.programs.strings.remove.character;

import org.apache.commons.lang3.StringUtils;

public class StringRemoveCharacterExample5 {

	public static void main(String[] args) {

		String input = "hello +world ++";
		char removalCh = '+';

		String output = StringUtils.remove(input, removalCh);

		System.out.println("Input string 1 : " + input);
		System.out.println("Output string after removing the + symbol : " + output);
	}
}

6. Conclusion


In this article, we've seen how to delete or remove the character from the string in java 8 and using third party api's.


No comments:

Post a Comment

Please do not add any spam links in the comments section.