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; } }
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.
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.
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.
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); // ...
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