fork(1) download
  1. import java.util.Set;
  2. import java.util.HashSet;
  3.  
  4. class StringUtilities
  5. {
  6. public static void main(String[] args)
  7. {
  8. String test = "Banana";
  9.  
  10. System.out.println("Test string \"" + test + "\" with duplicates removed is: \"" + removeDuplicates(test) + "\"");
  11. }
  12.  
  13. public static String removeDuplicates(final String input) {
  14. Set<Character> knownCharacters = new HashSet<>(input.length());
  15. StringBuilder noDuplicates = new StringBuilder(input.length());
  16.  
  17. for(char character : input.toCharArray()){
  18. if(!knownCharacters.contains(character)){
  19. knownCharacters.add(character);
  20. noDuplicates.append(character);
  21. }
  22. }
  23. return noDuplicates.toString();
  24. }
  25. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
Test string "Banana" with duplicates removed is: "Ban"