How can I find an index of a certain value in a Java array of type int
?
I tried using Arrays.binarySearch
on my unsorted array, it only sometimes gives the correct answer.
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.
To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.
int indexOf(int ch) : It returns the index of the first occurrence of character ch in a given String. int indexOf(int ch, int fromIndex) : It returns the index of first occurrence of character ch in the given string after the specified index “fromIndex”. For example, if the indexOf() method is called like this str.
To find the index of an element in a list, you use the index() function. It returns 3 as expected.
Integer[] array = {1,2,3,4,5,6}; Arrays.asList(array).indexOf(4);
Note that this solution is threadsafe because it creates a new object of type List.
Also you don't want to invoke this in a loop or something like that since you would be creating a new object every time
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