Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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 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?

like image 579
Jose L Martinez-Avial Avatar asked Dec 09 '10 07:12

Jose L Martinez-Avial


People also ask

How do you get the index of an item in a list in Java?

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.

Does set have index in Java?

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.

Does HashSet have index?

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.


1 Answers

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"; 
like image 158
Kiryl Ivanou Avatar answered Sep 20 '22 06:09

Kiryl Ivanou