Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
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?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe