Search code examples
listsetunique

Is there a Java collection whose objects are unique (as in a set) but has the ability to get the index/position of a certain object(as in a list)?


I have an ordered, unique, set of objects. I am currently using a TreeSet in order to get the ordering correct. However, sets do not have the ability to get index.

My current implementation is fine, but not necessarily intuitive.

TreeSet<T> treeSet = new TreeSet<T>(Comparable c);
// Omitted: Add items to treeSet //
int index = new ArrayList<T>(treeSet)().indexOf(object);

Is there an easier way to do this?


Solution

  • treeSet.headSet(object).size() should do the trick:

    import java.util.SortedSet;
    import java.util.TreeSet;
    
    class Test {
    
      public static void main(String[] args) {
    
        SortedSet<String> treeSet = new TreeSet<String>();
        String first = "index 0";
        String second = "index 1";
        treeSet.add(first);
        treeSet.add(second);
    
        int one = treeSet.headSet(second).size();
    
        System.out.println(one);
        // 1
      }
    }