Remove duplicate characters in a String using Java 8 Stream



 Write a Java 8 program that removes the duplicate characters from the given string.

Java Program to Remove duplicate characters

import java.util.Arrays;
import java.util.stream.Collectors;

public final class Strings {

    public static String removeDuplicates(String str) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return "";
        }

        return Arrays.asList(str.split("")).stream()
                .distinct()
                .collect(Collectors.joining());
    }
}

Test

public class Main {

    private static final String TEXT = "!ABCBA;C D E-D  D  DFA;";

    public static void main(String[] args) {

        System.out.println("Input text: \n" + TEXT + "\n");
        String resultV1 = Strings.removeDuplicates(TEXT);
        System.out.println("String with no duplicates: \n" + resultV1);
    }
}

Output:

Input text: 
!ABCBA;C D E-D  D  DFA;

String with no duplicates: 
!ABC; DE-F

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments