Как найти индекс элемента в массиве в Java?
Я ищу, чтобы найти индекс данного элемента, зная его содержимое, в Java.
Я попробовал следующий пример, который не работает:
Может кто-нибудь объяснить, что не так с этим и что мне нужно сделать, чтобы исправить это?
11 ответов
В этом случае вы можете создать новую строку String из своего массива символов, а затем сделать indeoxOf ( «e» ) в этой строке:
Но в других случаях примитивных типов данных вам придется перебирать его.
Это даже не действительный синтаксис. И вы пытаетесь сравнить со строкой. Для массивов вам придется самостоятельно пройти массив:
Если вы используете коллекцию, например ArrayList<Character> , вы также можете использовать метод indexOf() :
Существует также класс Arrays , который сокращает код выше:
Я считаю, что самый лучший способ — это вручную перебирать массив.
Для примитивных массивов
Начиная с Java 8, решение общего назначения для примитивного массива arr и значение для поиска val :
Этот код создает поток по индексам массива с IntStream.range , фильтрует индексы, чтобы сохранить только те, где элемент массива в этом индексе равен искомому значению, и, наконец, сохраняет первый, сопоставляемый с findFirst . findFirst возвращает OptionalInt , так как возможно, что совпадающие индексы не найдены. Поэтому мы вызываем orElse(-1) , чтобы либо вернуть найденное значение, либо -1 , если их не было найдено.
Для int[] , long[] и т.д. могут быть добавлены перегрузки. Тело метода останется прежним.
Для массивов объектов
Для массивов объектов, таких как String[] , мы могли бы использовать ту же идею и иметь шаг фильтрации, используя метод equals , или Objects.equals , чтобы рассмотреть два элемента null , вместо == .
Но мы можем сделать это проще:
Создает оболочку списка для входного массива с помощью Arrays.asList и ищет индекс элемента indexOf .
Это решение не работает для примитивных массивов как показано здесь: примитивный массив вроде int[] не является Object[] , а Object ; как таковой, вызов asList на нем создает список одного элемента, который является данным массивом, а не списком элементов массива.
Найти индекс элемента в данном массиве в Java
В этом посте будет обсуждаться, как найти индекс элемента в массиве примитивов или объектов в Java.
Решение должно либо возвращать индекс первого вхождения требуемого элемента, либо -1, если его нет в массиве.
1. Наивное решение — линейный поиск
Наивное решение состоит в том, чтобы выполнить линейный поиск в заданном массиве, чтобы определить, присутствует ли целевой элемент в массиве.
⮚ Для примитивных массивов:
⮚ Для массивов объектов:
2. Использование потока Java 8
Мы можем использовать Java 8 Stream для поиска индекса элемента в массиве примитивов и объектов, как показано ниже:
⮚ Для примитивных массивов:
⮚ Для массивов объектов:
3. Преобразовать в список
Идея состоит в том, чтобы преобразовать данный массив в список и использовать List.indexOf() метод, который возвращает индекс первого вхождения указанного элемента в этом списке.
⮚ Для примитивных массивов:
⮚ Для массивов объектов:
4. Бинарный поиск отсортированных массивов
Для отсортированных массивов мы можем использовать Алгоритм бинарного поиска для поиска указанного массива для указанного значения.
⮚ Для примитивных массивов:
⮚ Для массивов объектов:
5. Использование библиотеки Guava
⮚ Для примитивных массивов:
Библиотека Guava предоставляет несколько служебных классов, относящихся к примитивам, например Ints для инт, Longs надолго, Doubles на двоих, Floats для поплавка, Booleans для логического значения и так далее.
Каждый класс полезности имеет indexOf() метод, который возвращает индекс первого появления цели в массиве. Мы также можем использовать lastIndexOf() чтобы вернуть индекс последнего появления цели в массиве.
Java Array Indexof
This article introduces how to get the index of an array in Java using different techniques.
Please enable JavaScript
Get Index of an Element in an Integer Type Array in Java
There is no indexOf() method for an array in Java, but an ArrayList comes with this method that returns the index of the specified element. To access the indexOf() function, we first create an array of Integer and then convert it to a list using Arrays.asList() .
Notice that we use a wrapper class Integer instead of a primitive int because asList() only accepts wrapper classes, but they do return the result as a primitive data type. We can check the following example, where we specify the element i.e. 8 to the indexOf() method to get its index. The result we get from getIndex is of the int type.
Get Index of an Array Element Using Java 8 Stream API in Java
We can use the Stream API to filter out the array items and get the position of the specified element. IntStream is an interface that allows a primitive int to use the Stream functions like filter and range .
range() is a method of IntStream that returns the elements from the starting position till the end of the array. Now we use filter() that takes a predicate as an argument. We use i -> elementToFind == array1[i] as the predicate where i is the value received from range() and elementToFind == array1[i] is the condition to check if the elementToFind matches with the current element of the array1 .
findFirst() returns the first element and orElse() returns -1 if the condition fails.
Get Index of an Array Element Using ArrayUtils.indexOf() in Java
This example uses the ArrayUtls class that is included in the Apache Commons Library. We use the below dependency to import the library functions to our project.
We use the indexOf() function of the ArrayUtils class to find the index of the array. indexOf() accepts two arguments, the first argument is the array, and the second argument is the element of which we want to find the index.
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
How to find index of Element in Java Array?
You can find the index of an element in an array in many ways like using a looping statement and finding a match, or by using ArrayUtils from commons library.
In this tutorial, we will go through each of these process and provide example for each one of them for finding index of an element in an array.
Find Index of Element in Array using Looping Technique
Using While Loop
In the following example, we will use while loop to find the index of first occurrence of a given element in array. We shall use while loop to traverse the array elements, and when we find a match, we have the required index.
Java Program
Output
If the given element is present in the array, we get an index that is non negative. If the given element is not present, the index will have a value of -1.
Using For Loop
In the following example, we will use for loop to find the index of a given element in array.
Java Program
Output
If the given element is present in the array, we get an index that is non negative. If the given element is not present, the index will have a value of -1.
Find Index of Element in Array using Looping ArrayUtils
ArrayUtils.indexOf(array, element) method finds the index of element in array and returns the index.
Java Program
Output
Conclusion
In this Java Tutorial, we learned how to find the index of an given element in the array, with the help of example Java programs.