Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain index of a given LinkedHashSet element without iteration?

Is it even possible?

Say you have

private Set<String> names = new LinkedHashSet<String>(); 

and Strings are "Mike", "John", "Karen".

Is it possible to get "1" in return to "what's the index of "John" without iteration?

The following works fine .. with this question i wonder if there is a better way

for (String s : names) {     ++i;     if (s.equals(someRandomInputString)) {         break;     } } 
like image 697
James Raitsev Avatar asked Aug 15 '11 18:08

James Raitsev


People also ask

How do I find the index of a element in LinkedHashSet?

To find the element index in Java, we can create a new user-defined function (indexOf) that returns the given element index. Our function iterate LinkedHashSet and returns the index of the given element. Note: If the element is not present in the LinkedHashSet, it returns -1.

Can we use get method in LinkedHashSet?

Method 3: LinkedHashSet to be converted to List to get the desired element at the given index. Convert our LinkedHashMap to List like ArrayList. Using get() method to get an element in a given index.

Can we get index of set in Java?

The indexOf(Object) method of the java. util. ArrayList class returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. Using this method, you can find the index of a given element.


1 Answers

The Set interface doesn't have something like as an indexOf() method. You'd really need to iterate over it or to use the List interface instead which offers an indexOf() method.

If you would like to, converting Set to List is pretty trivial, it should be a matter of passing the Set through the constructor of the List implementation. E.g.

List<String> nameList = new ArrayList<String>(nameSet); // ... 
like image 63
BalusC Avatar answered Oct 01 '22 19:10

BalusC