Remove duplicate characters from a String in Java

You have been given a string and you need to remove duplicate characters from it. For ex. given String is "Hello" and the output should be "Helo".

This can be achieved in two ways. Lets go for it one by one.


1) Using Array of Char

package com.infybuzz.string;

public class RemoveDuplicateChars1 {

 public static void main(String[] args) {
  
  String str = "infybuzz";
  
  String result = "";
  
  char[] charArray = str.toCharArray();
  
  for (Character ch : charArray) {
   
   if (!result.contains(ch.toString())) {
    result += ch;
   }
   
  }
  
  System.out.println(result);
  
 }

}

Output


infybuz


2) Using List and StringBuilder

package com.infybuzz.string;

import java.util.ArrayList;
import java.util.List;

public class RemoveDuplicateChars2 {

 public static void main(String[] args) {
  
  String str = "infybuzz";
  
  List<Character> charList = new ArrayList<Character>();
  
  char[] charArray = str.toCharArray();
  
  for (Character ch : charArray) {
   
   if (!charList.contains(ch)) {
    charList.add(ch);
   }
   
  }
  
  StringBuilder stringBuilder = new StringBuilder();
  
  for (Character ch: charList) {
   stringBuilder.append(ch);
  }
  
  System.out.println(stringBuilder.toString());
  
 }

}

Output


infybuz