Java массив индекс элемента

Как найти индекс массива java

Чтобы найти индекс искомого элемента в массиве можно в цикле перебрать все элементы и сравнить их с искомым. Если они равны, будет выведен индекс первого подходящего элемента.

// Число, которое будем искать int num = 3; // Переменная для хранения индекса, // найденного числа int index = -1; int[] arr = 1, 2, 3, 4, 5>; for (int i = 0; i  arr.length; i++)  // Если элемент и число равны, то // сохраняй индекс if (arr[i] == num)  index = i; > > System.out.println(index); // => 2 

Также можно воспользоваться пакетом org.apache.commons.lang , методом indexOf() из класса ArrayUtils для нахождения индекса элемента.

import org.apache.commons.lang3.ArrayUtils; public class Example  public static void main(String[] args)  int[] arr = 1, 2, 3, 4, 5>; // индекс числа 3 int index = ArrayUtils.indexOf(arr, 3); System.out.println(index); // => 2 > > 

Источник

Найти индекс элемента в данном массиве в Java

В этом посте будет обсуждаться, как найти индекс элемента в массиве примитивов или объектов в Java.

Решение должно либо возвращать индекс первого вхождения требуемого элемента, либо -1, если его нет в массиве.

1. Наивное решение — линейный поиск

Наивное решение состоит в том, чтобы выполнить линейный поиск в заданном массиве, чтобы определить, присутствует ли целевой элемент в массиве.

2. Использование потока Java 8

Мы можем использовать Java 8 Stream для поиска индекса элемента в массиве примитивов и объектов, как показано ниже:

3. Преобразовать в список

Идея состоит в том, чтобы преобразовать данный массив в список и использовать List.indexOf() метод, который возвращает индекс первого вхождения указанного элемента в этом списке.

4. Бинарный поиск отсортированных массивов

Для отсортированных массивов мы можем использовать Алгоритм бинарного поиска для поиска указанного массива для указанного значения.

5. Использование библиотеки Guava

Библиотека Guava предоставляет несколько служебных классов, относящихся к примитивам, например Ints для инт, Longs надолго, Doubles на двоих, Floats для поплавка, Booleans для логического значения и так далее.

Каждый класс полезности имеет indexOf() метод, который возвращает индекс первого появления цели в массиве. Мы также можем использовать lastIndexOf() чтобы вернуть индекс последнего появления цели в массиве.

Guava’s com.google.commons.collect.Iterables класс содержит статический служебный метод indexOf(Iterator, Predicate) который возвращает индекс первого элемента, удовлетворяющего предоставленному предикату, или -1, если итератор не имеет таких элементов.

Источник

Как найти индекс элемента в массиве java

Чтобы найти индекс элемента в массиве в Java , можно воспользоваться циклом for и проверять каждый элемент на равенство искомому. Как только элемент будет найден, можно вернуть его индекс. Если элемент не найден, можно вернуть -1 или выбросить исключение.

public static int findIndex(int[] arr, int element)  for (int i = 0; i  arr.length; i++)  if (arr[i] == element)  return i; > > return -1; // если элемент не найден > 

Для того, чтобы найти индекс элемента в массиве в Java , можно использовать метод indexOf класса java.util.Arrays Этот метод принимает на вход массив и искомый элемент, и возвращает индекс первого вхождения элемента в массиве. Если элемент не найден, метод возвращает -1.

Например, чтобы найти индекс числа 42 в массиве numbers , можно написать следующий код:

int[] numbers = 10, 20, 30, 40, 42, 50>; int index = Arrays.indexOf(myArray, 42); // 4 

Источник

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

public class ArrayExample < public static void main(String[] args) < int[] numbers = ; int element = 2; int index = -1; int i = 0; while(i < numbers.length) < if(numbers[i] == element) < index = i; break; >i++; > System.out.println("Index of "+element+" is : "+index); > >

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

public class ArrayExample < public static void main(String[] args) < int[] numbers = ; int element = 2; int index = -1; for(int i = 0; i < numbers.length; i++) < if(numbers[i] == element) < index = i; break; >> System.out.println("Index of "+element+" is : "+index); > >

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

import org.apache.commons.lang.ArrayUtils; public class ArrayExample < public static void main(String[] args) < int[] numbers = ; int element = 2; int index = ArrayUtils.indexOf(numbers, element); System.out.println("Index of "+element+" is : "+index); > >

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.

Источник

Java Array Indexof

Java Array Indexof

  1. Get Index of an Element in an Integer Type Array in Java
  2. Get Index of an Array Element Using Java 8 Stream API in Java
  3. Get Index of an Array Element Using ArrayUtils.indexOf() in Java

This article introduces how to get the index of an array in Java using different techniques.

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.

import java.util.Arrays;  public class ArrayIndexOf   public static void main(String[] args)   Integer[] array1 = 2, 4, 6, 8, 10>;   int getIndex = Arrays.asList(array1).indexOf(8);   System.out.println("8 is located at "+getIndex+" index");  > > 

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.

import java.util.stream.IntStream;  public class ArrayIndexOf   public static void main(String[] args)   int[] array1 = 1, 3, 5, 7, 9>;   int elementToFind = 3;   int indexOfElement = IntStream.range(0, array1.length).  filter(i -> elementToFind == array1[i]).  findFirst().orElse(-1);   System.out.println("Index of " + elementToFind + " is " + indexOfElement);   > > 

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.

   org.apache.commons   commons-lang3   3.11  

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.

import org.apache.commons.lang3.ArrayUtils;  public class ArrayIndexOf   public static void main(String[] args)   int[] array1 = 1, 3, 5, 7, 9>;   int elementToFind = 9;   int indexOfElement = ArrayUtils.indexOf(array1, elementToFind);  System.out.println("Index of " + elementToFind + " is " + indexOfElement);   > > 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Related Article — Java Array

Copyright © 2023. All right reserved

Источник

Читайте также:  Http запросы android kotlin
Оцените статью