w3resource

Java String Exercises: Print after removing duplicates from a given string

Java String: Exercise-38 with Solution

Write a Java program to print after removing duplicates from a given string.

Pictorial Presentation:

Java String Exercises: Print after removing duplicates from a given string

Sample Solution:

Java Code:

import java.util.*;
public class Main {
 public static void main(String[] args) {
  String str1 = "w3resource";
  System.out.println("The given string is: " + str1);
  System.out.println("After removing duplicates characters the new string is: " + removeDuplicateChars(str1));
 }
 private static String removeDuplicateChars(String sourceStr) {
  char[] arr1 = sourceStr.toCharArray();
  String targetStr = "";
  for (char value: arr1) {
   if (targetStr.indexOf(value) == -1) {
    targetStr += value;
   }
  }
  return targetStr;
 }
}

Sample Output:

The given string is: w3resource
After removing duplicates characters the new string is: w3resouc

Flowchart:

Flowchart: Java String Exercises - Print after removing duplicates from a given string

Visualize Java code execution (Python Tutor):


Remove duplicate characters from a given string.

Main.java Code:

//MIT License: https://bit.ly/35gZLa3
import java.util.concurrent.TimeUnit;

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");

        System.out.println("StringBuilder and indexOf() solution:");
        long startTimeV1 = System.nanoTime();

        String resultV1 = Strings.removeDuplicatesV1(TEXT);

        displayExecutionTime(System.nanoTime() - startTimeV1);
        System.out.println("String with no duplicates: \n" + resultV1);

        System.out.println();
        System.out.println("LinkedHashSet and StringBuilder solution:");
        long startTimeV2 = System.nanoTime();

        String resultV2 = Strings.removeDuplicatesV2(TEXT);

        displayExecutionTime(System.nanoTime() - startTimeV2);
        System.out.println("String with no duplicates: \n" + resultV2);

        System.out.println();
        System.out.println("Java 8, functional-style solution:");
        long startTimeV3 = System.nanoTime();

        String resultV3 = Strings.removeDuplicatesV3(TEXT);

        displayExecutionTime(System.nanoTime() - startTimeV3);
        System.out.println("String with no duplicates: \n" + resultV3);
    }

    private static void displayExecutionTime(long time) {
        System.out.println("Execution time: " + time + " ns" + " ("
                + TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS) + " ms)");
    }
}

Strings.java Code:

//MIT License: https://bit.ly/35gZLa3
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public final class Strings {

    private Strings() {
        throw new AssertionError("Cannot be instantiated");
    }

    public static String removeDuplicatesV1(String str) {

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

        char[] chArray = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (char ch : chArray) {
            if (sb.indexOf(String.valueOf(ch)) == -1) {
                sb.append(ch);
            }
        }

        return sb.toString();
    }

    public static String removeDuplicatesV2(String str) {

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

        char[] chArray = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        Set<Character> chHashSet = new HashSet<>();
        for (char c : chArray) {
            if (chHashSet.add(c)) {
                sb.append(c);
            }

        }
        return sb.toString();
    }

    public static String removeDuplicatesV3(String str) {

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

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

Sample Output:

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

StringBuilder and indexOf() solution:
Execution time: 760557 ns (0 ms)
String with no duplicates: 
!ABC; DE-F

LinkedHashSet and StringBuilder solution:
Execution time: 705992 ns (0 ms)
String with no duplicates: 
!ABC; DE-F

Java 8, functional-style solution:
Execution time: 84676685 ns (84 ms)
String with no duplicates: 
!ABC; DE-F

Flowchart:

Flowchart: Java String Exercises - Remove duplicate characters
Flowchart: Java String Exercises - Remove duplicate characters

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to find length of the longest substring of a given string without repeating characters.
Next: Write a Java program to find first non repeating character in a string.

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH