javacodex.com
Java Examples
Java Examples
memu home questions

Using a HashSet to determine if a String has all unique characters

UniqueChar.java

import java.util.HashSet;
 
public class UniqueChar {
 
   public static void main(String[] args) {
      String str1 = "abcdefghijk";
      String str2 = "abcdefghijka";
      System.out.println(str1 + ":" + isUnique(str1));
      System.out.println(str2 + ":" + isUnique(str2));
   }
 
   public static boolean isUnique(String str) {
      boolean result = false;
      HashSet< Character> hashset = new HashSet();
      for (int i = 0; i < str.length(); i++) {
         result = hashset.add(str.charAt(i));
         if (result == false) {
            return false;
         }
      }
      return true;
   }
}
 

output

$ java UniqueChar
abcdefghijk:true
abcdefghijka:false

Questions answered by this page:

How to check if a string has all unique characters Determine if string has all unique characters Find out if a string has all unique characters Use a HashSet to determine if a String has all unique characters




Contact: javacodex@yahoo.com