-4

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

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

3 Answers3

4

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]

davidxxx
  • 125,838
  • 23
  • 214
  • 215
4

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.

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
1
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        
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
  • 1
    Just saying, but using [`Set.add`](https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#add(E)) would be enough, it return `true` if it was not present. so `if( ! exists.add(s.toLower()) return true;` – AxelH Sep 13 '17 at 13:44
  • 1
    I like this solution, it will stop on the first duplicate, way more effective ! – AxelH Sep 13 '17 at 13:50