Java 8 – Remove All Whitespaces from a String

Introduction

Whitespace characters (such as spaces, tabs, and newlines) are often used in strings for formatting, but there are scenarios where you need to remove them. Whether you’re processing user input, cleaning up data, or formatting text for storage or display, removing all whitespaces from a string is a common requirement. Java 8 provides a concise and powerful way to achieve this using Streams. In this guide, we’ll explore how to remove all whitespaces from a string using both the traditional approach and Java 8 Streams.

Problem Statement

The task is to create a Java program that:

  • Accepts a string as input.
  • Removes all whitespace characters from the string.
  • Outputs the resulting string with no whitespaces.

Example 1:

  • Input: "Hello World"
  • Output: "HelloWorld"

Example 2:

  • Input: " Java 8 Streams "
  • Output: "Java8Streams"

Solution Steps

  1. Input String: Start with a string that can either be hardcoded or provided by the user.
  2. Remove Whitespaces (Traditional Approach): Use a StringBuilder and loop through each character to exclude whitespaces.
  3. Remove Whitespaces (Java 8 Streams): Use the Stream API to filter out whitespace characters and collect the result.
  4. Display the Result: Print the string with all whitespaces removed.

Java Program

Traditional Approach: Remove All Whitespaces from a String

/**
 * Traditional Approach: Remove All Whitespaces from a String
 * Author: https://www.rameshfadatare.com/
 */
public class RemoveWhitespacesTraditional {

    public static void main(String[] args) {
        // Step 1: Take input string
        String input = "Hello World";

        // Step 2: Remove whitespaces using traditional approach
        String result = removeWhitespacesTraditional(input);

        // Step 3: Display the result
        System.out.println("String without whitespaces: " + result);
    }

    // Method to remove all whitespaces from a string (traditional approach)
    public static String removeWhitespacesTraditional(String str) {
        StringBuilder result = new StringBuilder();
        for (char c : str.toCharArray()) {
            if (!Character.isWhitespace(c)) {
                result.append(c);
            }
        }
        return result.toString();
    }
}

Java 8 Approach: Remove All Whitespaces from a String

/**
 * Java 8: Remove All Whitespaces from a String
 * Author: https://www.rameshfadatare.com/
 */
public class RemoveWhitespacesJava8 {

    public static void main(String[] args) {
        // Step 1: Take input string
        String input = " Java 8 Streams ";

        // Step 2: Remove whitespaces using Java 8 Streams
        String result = removeWhitespacesJava8(input);

        // Step 3: Display the result
        System.out.println("String without whitespaces: " + result);
    }

    // Method to remove all whitespaces from a string (Java 8 Streams approach)
    public static String removeWhitespacesJava8(String str) {
        return str.chars()
                  .filter(c -> !Character.isWhitespace(c))
                  .mapToObj(c -> String.valueOf((char) c))
                  .collect(Collectors.joining());
    }
}

Explanation of the Programs

  • Traditional Approach: The first program uses a StringBuilder to build the result string. It iterates through each character in the input string, appending only non-whitespace characters to the result.

  • Java 8 Approach: The second program leverages the Stream API. The chars() method converts the string into an IntStream, and filter() is used to exclude whitespace characters. The mapToObj() method converts each character back to a string, and Collectors.joining() combines them into the final result.

Output Example

For both methods, the output will be:

Example 1:

Input: Hello World
Output: String without whitespaces: HelloWorld

Example 2:

Input:  Java 8 Streams 
Output: String without whitespaces: Java8Streams

Advanced Considerations

  1. Handling Different Types of Whitespace: Both methods handle all types of whitespace characters, including spaces, tabs, and newlines.

  2. Performance Considerations: Both methods are efficient for typical string lengths. The traditional method is straightforward and easy to understand, while the Java 8 approach is more concise and leverages modern Java features.

  3. Edge Cases: If the input string is empty or contains only whitespaces, both methods correctly return an empty string.

Conclusion

This guide provides two methods for removing all whitespaces from a string: the traditional approach using a StringBuilder and a more modern approach using Java 8 Streams. Both methods are effective, but the Java 8 approach offers a more functional and concise solution. Depending on your needs and the style of your codebase, either method can be used to achieve the desired result.

Leave a Comment

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

Scroll to Top