w3resource

Java String Exercises: Remove duplicate characters from a given string presents in another given string

Java String: Exercise-41 with Solution

Write a Java program to remove duplicate characters from a given string presents in another given string.

Pictorial Presentation:

Java String Exercises: Remove duplicate characters from a given string presents in another given string

Sample Solution-1:

Java Code:

import java.util.*;
public class Main {
 public static void main(String[] args) {
  String str1 = "the quick brown fox";
  String str2 = "queen";
  System.out.println("The given string is: " + str1);
  System.out.println("The given mask string is: " + str2);
  char arr[] = new char[str1.length()];
  char[] mask = new char[256];
  for (int i = 0; i < str2.length(); i++)
   mask[str2.charAt(i)]++;
  System.out.println("\nThe new string is: ");
  for (int i = 0; i < str1.length(); i++) {
   if (mask[str1.charAt(i)] == 0)
    System.out.print(str1.charAt(i));
  }
 }
}

Sample Output:

The given string is: the quick brown fox
The given mask string is: queen

The new string is: 
th ick brow fox

Flowchart:

Flowchart: Java String Exercises - Remove duplicate characters from a given string presents in another given string

Sample Solution-2:

Main.java Code:

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

public class Main {

    private static final String TEXT = "Be strong, be fearless, be beautiful. "
            + "And believe that anything is possible when you have the right "
            + "people there to support you. ";
    // Ӝ -> Unicode: \u04DC, Code Point: 1244
    // 💕 -> Unicode: \uD83D\uDC95, Code Point: 128149
    // 🎼 -> \uD83C\uDFBC, Code Point: 127932
    // 😍 ->\uD83D\uDE0D, Code Point: 128525
    private static final String TEXT_CP = TEXT + "😍 I love 💕 you Ӝ so much 💕 😍 🎼🎼🎼!";
       
    public static void main(String[] args) {
        
        System.out.println("Input text: \n" + TEXT + "\n");
        
        System.out.println("\n\nASCII or 16 bits Unicode characters (less than 65,535 (0xFFFF)) examples:\n");
        
        System.out.println("HashMap based solution:");
        long startTimeV1 = System.nanoTime();
        
        Map<Character, Integer> duplicatesV1 = Strings.countDuplicateCharactersV1(TEXT);
        
        displayExecutionTime(System.nanoTime()-startTimeV1);
        System.out.println(Arrays.toString(duplicatesV1.entrySet().toArray()));
        // or: duplicatesV1.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));
        
        System.out.println();        
        System.out.println("Java 8, functional-style solution:");
        long startTimeV2 = System.nanoTime();
        
        Map<Character, Integer> duplicatesV2 = Strings.countDuplicateCharactersV2(TEXT);
        
        displayExecutionTime(System.nanoTime()-startTimeV2);
        System.out.println(Arrays.toString(duplicatesV2.entrySet().toArray()));
        // or: duplicatesV2.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));
        
        System.out.println("\n--------------------------------------\n");        
        System.out.println("Input text: \n" + TEXT_CP + "\n");
        System.out.println("\n\nIncluding Unicode surrogate pairs examples:\n");
        System.out.println("HashMap based solution:");
        long startTimeV3 = System.nanoTime();
        
        Map<String, Integer> duplicatesV3 = Strings.countDuplicateCharactersVCP1(TEXT_CP);
        
        displayExecutionTime(System.nanoTime()-startTimeV3);
        System.out.println(Arrays.toString(duplicatesV3.entrySet().toArray()));
        // or: duplicatesV3.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));
        
        System.out.println();        
        System.out.println("Java 8, functional-style solution:");
        long startTimeV4 = System.nanoTime();
        
        Map<String, Integer> duplicatesV4 = Strings.countDuplicateCharactersVCP2(TEXT_CP);
        
        displayExecutionTime(System.nanoTime()-startTimeV4);
        System.out.println(Arrays.toString(duplicatesV4.entrySet().toArray()));
        // or: duplicatesV4.forEach( (k, v) -> System.out.print(k + "="+ v + ", "));        
    }
    
    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.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public final class Strings {

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

    public static Map<Character, Integer> countDuplicateCharactersV1(String str) {

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

        Map<Character, Integer> result = new HashMap<>();                

        // or use for(char ch: str.toCharArray()) { ... }
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            result.compute(ch, (k, v) -> (v == null) ? 1 : ++v);
        }

        return result;
    }

    public static Map<String, Integer> countDuplicateCharactersVCP1(String str) {

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

        Map<String, Integer> result = new HashMap<>();

        for (int i = 0; i < str.length(); i++) {
            
            /*
            String ch = String.valueOf(Character.toChars(str.codePointAt(i)));
            if (i < str.length() - 1 && str.codePointCount(i, i + 2) == 1) {
                i++;
            }
            */
            
            // or, like this (this code produce the same result as the commented code above
            int cp = str.codePointAt(i);
            String ch = String.valueOf(Character.toChars(cp));
            if(Character.charCount(cp) == 2) { // 2 means a suroggate pair
                i++;
            }

            result.compute(ch, (k, v) -> (v == null) ? 1 : ++v);
        }

        return result;
    }

    public static Map<Character, Integer> countDuplicateCharactersV2(String str) {

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

        Map<Character, Integer> result = str.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

        return result;
    }

    public static Map<String, Integer> countDuplicateCharactersVCP2(String str) {

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

        Map<String, Integer> result = str.codePoints()
                .mapToObj(c -> String.valueOf(Character.toChars(c)))
                .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

        return result;
    }
}

Sample Output:

Input text: 
Be strong, be fearless, be beautiful. And believe that anything is possible when you have the right people there to support you. 



ASCII or 16 bits Unicode characters (less than 65,535 (0xFFFF)) examples:

HashMap based solution:
Execution time: 89574632 ns (89 ms)
[ =22, A=1, a=5, b=5, B=1, d=1, e=17, f=2, g=3, h=7, i=6, l=5, ,=2, .=2, n=5, o=7, p=5, r=5, s=7, t=10, u=5, v=2, w=1, y=3]

Java 8, functional-style solution:
Execution time: 232078057 ns (232 ms)
[ =22, A=1, a=5, b=5, B=1, d=1, e=17, f=2, g=3, h=7, i=6, l=5, ,=2, .=2, n=5, o=7, p=5, r=5, s=7, t=10, u=5, v=2, w=1, y=3]

--------------------------------------

Input text: 
Be strong, be fearless, be beautiful. And believe that anything is possible when you have the right people there to support you. 😍 I love 💕 you Ӝ so much 💕 😍 🎼🎼🎼!



Including Unicode surrogate pairs examples:

HashMap based solution:
Execution time: 1478360 ns (1 ms)
[A=1, B=1, I=1, 🎼=3, Ӝ=1,  =32, !=1, a=5, b=5, c=1, 💕=2, d=1, e=18, f=2, g=3, h=8, i=6, 😍=2, l=6, ,=2, m=1, .=2, n=5, o=10, p=5, r=5, s=8, t=10, u=7, v=3, w=1, y=4]

Java 8, functional-style solution:
Execution time: 2797489 ns (2 ms)
[A=1, B=1, I=1, 🎼=3, Ӝ=1,  =32, !=1, a=5, b=5, c=1, 💕=2, d=1, e=18, f=2, g=3, h=8, i=6, 😍=2, l=6, ,=2, m=1, .=2, n=5, o=10, p=5, r=5, s=8, t=10, u=7, v=3, w=1, y=4]

Flowchart:

Flowchart: Java String Exercises - Remove duplicate characters from a given string presents in another given string
Flowchart: Java String Exercises - Remove duplicate characters from a given string presents in another given string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to divide a string in n equal parts.
Next: Write a Java program to print list items containing all characters of a given word.

What is the difficulty level of this exercise?



Java: Tips of the Day

Count the number of occurrences of a char in a String:

int count = StringUtils.countMatches("a.b.c.d", ".");

Ref: https://bit.ly/2OTy6sG