Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add unique letters of a given String to a List

I want to add a String's letters to a list, but I only want to add each letter once. For example, if the String is "HELLO AM CHRISTOS WHITE", some letters are appearing more than one time, so I want them to be added only one time.

I am thinking about two for loops:

for (int i=0; i< str.length(); i++){
    for(int j=0; j< str.length(); j++){
        if (str.charAt(i) != str.charAt(j)) {
            myList.add(charAt(i));
        }
    }
}

But this code does not avoid duplicates.

like image 485
Christos Michael Avatar asked Dec 16 '15 14:12

Christos Michael


3 Answers

It would be more efficient to use a LinkedHashSet for determining the unique characters. If you use a LinkedHashSet, the order of the unique characters of the input String will be preserved.

After a single loop, that would take linear time, you can add all the unique characters to your output List.

Set<Character> unique = new LinkedHashSet<>();
for (int i = 0; i < str.length(); i++){
    unique.add(str.charAt(i));
}
myList.addAll(unique);
like image 84
Eran Avatar answered Oct 07 '22 00:10

Eran


To prevent duplicates in a collection, you don't need List, you need a Set (such as HashSet).

If you want to preserve the order you're adding your Strings, use a LinkedHashSet.

Finally, if you want your Set to naturally sort your Strings (or to be able to sort them with a Comparator), use a TreeSet.

Example

String foo = "ghghababcdef";
Set<String> hash = new HashSet<>();
Set<String> linked = new LinkedHashSet<>();
Set<String> tree = new TreeSet<>();
// iterating characters
for (char c: foo.toCharArray()) {
    // adding String representation of character to each set
    hash.add(Character.toString(c));
    linked.add(Character.toString(c));
    tree.add(Character.toString(c));
}
// printing...
System.out.println(hash);
System.out.println(linked);
System.out.println(tree);

Output

[a, b, c, d, e, f, g, h] // this may vary
[g, h, a, b, c, d, e, f] // keeps insertion order
[a, b, c, d, e, f, g, h] // sorted lexicographically by default
like image 39
Mena Avatar answered Oct 06 '22 23:10

Mena


as an alternative to the Set answer if you want to stick to the List solution. You only need to loop once and make use of the List.contains(Object) method and check if the current char is already present in your List.

String str = "HELLO AM CHRISTOS WHITE";
List<Character> myList = new ArrayList<>();
for(int i=0; i< str.length(); i++){
    if (!myList.contains(str.charAt(i))) {
        myList.add(str.charAt(i));
    }
}
for(char c : myList) {
    System.out.println(c);
}

output

HELO AMCRISTW

like image 26
SomeJavaGuy Avatar answered Oct 07 '22 00:10

SomeJavaGuy