javalinkedhashset

find the index of unique values in LinkedHashSet


I'm using LinkedHashSet to get all the unique values from an ArrayList.

My code looks as following:

Set<String> set = new LinkedHashSet<>( filteredTitles );
filteredTitles.clear();
filteredTitles.addAll( set );

For example if filteredTitles was equals to ["a","b","c","a"] It will return me ["a","b","c"].

How can I get the index of the unique values? for example here [1,2,3] since 4 is not unique already.

Thank you


Solution

  • How can I get the index of the unique values?

    Here is one way of doing it using a map.

    List<String> list = List.of("a","b","e","c","a","d","f","e","f","e","g");
    
     
    Set<String> seen = new HashSet<>();
    Map<String,Integer> uniquePair = new HashMap<>();
    for (int i = 0; i < list.size(); i++) {
        String str = list.get(i);
        if (seen.add(str)) { // if not seen already, add to map
           uniquePair.put(str, i);
           continue;
        }
        uniquePair.remove(str); // oops, not unique, remove from map.
    }
      
    uniquePair.entrySet().forEach(System.out::println);
    

    prints

    b=1
    c=3
    d=5
    g=10