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 elements, 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?
The standard solution to find the index of an element in a List is using the indexOf() method. It returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.
Unlike List, Set DOES NOT allow you to add duplicate elements. Set allows you to add at most one null element only. Set interface got one default method in Java 8: spliterator. Unlike List and arrays, Set does NOT support indexes or positions of it's elements.
In HashSet you won't be able to find value by index. If you still want to find the element you have no other option but to use the iterator, it will iterate through the Hashset and give you one by one element from the Hashset. You want to find your element by index you should use ArrayList.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With