开发者

How to get index of an item in java.util.Set

I know the differences between Set and List(unique vs. duplications allowed, not ordered/ordered, etc). What I'm looking for is a set that keeps the elements ordered(that's easy), but I also need to be able to recover the index in which an element was inserted. So if I insert four elem开发者_JS百科ents, then I want to be able to know the order in which one of them was inserted.

MySet<String> set = MySet<String>();
set.add("one");
set.add("two");
set.add("three");
set.add("four");

int index = set.getIndex("two");

So at any given moment I can check if a String was already added, and get the index of the string in the set. Is there anything like this, or I need to implement it myself?


After creating Set just convert it to List and get by index from List:

Set<String> stringsSet = new HashSet<>();
stringsSet.add("string1");
stringsSet.add("string2");

List<String> stringsList = new ArrayList<>(stringsSet);
stringsList.get(0); // "string1";
stringsList.get(1); // "string2";


A small static custom method in a Util class would help:

 public static <T> int getIndex(Set<T> set, T value) {
   int result = 0;
   for (T entry:set) {
     if (entry.equals(value)) return result;
     result++;
   }
   return -1;
 }
  

If you need/want one class that is a Set and offers a getIndex() method, I strongly suggest to implement a new Set and use the decorator pattern:

 public class IndexAwareSet<T> implements Set {
   private Set<T> set;
   public IndexAwareSet(Set<T> set) {
     this.set = set;
   }

   // ... implement all methods from Set and delegate to the internal Set

   public int getIndex(T entry) {
     int result = 0;
     for (T entry:set) {
       if (entry.equals(value)) return result;
       result++;
     }
     return -1;
   }
 }


you can extend LinkedHashSet adding your desired getIndex() method. It's 15 minutes to implement and test it. Just go through the set using iterator and counter, check the object for equality. If found, return the counter.


One solution (though not very pretty) is to use Apache common List/Set mutation

import org.apache.commons.collections.list.SetUniqueList;

final List<Long> vertexes=SetUniqueList.setUniqueList(new LinkedList<>());

it is a list without duplicates

https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/index.html?org/apache/commons/collections/list/SetUniqueList.html


How about add the strings to a hashtable where the value is an index:

  Hashtable<String, Integer> itemIndex = new Hashtable<>();
  itemIndex.put("First String",1);
  itemIndex.put("Second String",2);
  itemIndex.put("Third String",3);

  int indexOfThirdString = itemIndex.get("Third String");


you can send your set data to a new list
Java ArrayList<String> myList = new ArrayList<>(); myList.addAll(uniqueNameSet); myList.indexOf("xxx");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜