I want to check that List<String>
doesn't contain duplicates ignore case
I understand that I can write construction like
for(...){
for(...){}
}
But I want to find nicer way
I want to check that List<String>
doesn't contain duplicates ignore case
I understand that I can write construction like
for(...){
for(...){}
}
But I want to find nicer way
You may create a List
with only String
in uppercase.
Then collect these elements into a Set
that removes all duplicates.
At last, compare the size of the Set
with the size of the List
: if the size differs between, it means that you have a least one duplicate.
Executable code :
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class RemoveDuplicateInsensitiveCaseString {
public static void main(String[] args) {
List<String> list = Arrays.asList("abort", "Abort", "accent", "ACCENT");
Set<String> set = list.stream().map(String::toUpperCase).collect(Collectors.toSet());
if (set.size() != list.size()){
// you have duplicate
System.out.println(set);
}
}
}
Output :
[ACCENT, ABORT]
Add the input list to a TreeSet
with a case-insensitive comparator, and check the size afterwards:
List<String> input = Arrays.asList("a", "A", "b");
Set<String> set = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
set.addAll(input);
boolean containsDuplicates = input.size() != set.size();
Update: Run it here.
List<String> origList;
Set<String> exists = new HashSet();
boolean dup = false;
for (String s : origList) {
if (!exists.add(s.toLower()) {
dup = true;
break;
}
}
// dup param will have your answer