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.
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);
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 String
s, use a LinkedHashSet
.
Finally, if you want your Set
to naturally sort your String
s (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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With