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 som
Integer[] array = {1, 2, 3, 4, 5, 6};
for (int i = 0; i < array.length; i++) {
if (array[i] == 4) {
system.out.println(i);
break;
}
}
In the main method using for loops: -the third for loop in my example is the answer to this question. -in my example I made an array of 20 random integers, assigned a variable the smallest number, and stopped the loop when the location of the array reached the smallest value while counting the number of loops.
import java.util.Random;
public class scratch {
public static void main(String[] args){
Random rnd = new Random();
int randomIntegers[] = new int[20];
double smallest = randomIntegers[0];
int location = 0;
for(int i = 0; i < randomIntegers.length; i++){ // fills array with random integers
randomIntegers[i] = rnd.nextInt(99) + 1;
System.out.println(" --" + i + "-- " + randomIntegers[i]);
}
for (int i = 0; i < randomIntegers.length; i++){ // get the location of smallest number in the array
if(randomIntegers[i] < smallest){
smallest = randomIntegers[i];
}
}
for (int i = 0; i < randomIntegers.length; i++){
if(randomIntegers[i] == smallest){ //break the loop when array location value == <smallest>
break;
}
location ++;
}
System.out.println("location: " + location + "\nsmallest: " + smallest);
}
}
Code outputs all the numbers and their locations, and the location of the smallest number followed by the smallest number.
/**
* Method to get the index of the given item from the list
* @param stringArray
* @param name
* @return index of the item if item exists else return -1
*/
public static int getIndexOfItemInArray(String[] stringArray, String name) {
if (stringArray != null && stringArray.length > 0) {
ArrayList<String> list = new ArrayList<String>(Arrays.asList(stringArray));
int index = list.indexOf(name);
list.clear();
return index;
}
return -1;
}
Integer[] arr = { 0, 1, 1, 2, 3, 5, 8, 13, 21 };
List<Integer> arrlst = Arrays.asList(arr);
System.out.println(arrlst.lastIndexOf(1));
ArrayUtils.indexOf(array, value);
Ints.indexOf(array, value);
Arrays.asList(array).indexOf(value);
In case anyone is still looking for the answer-
You can use ArrayUtils.indexOf() from the [Apache Commons Library][1].
If you are using Java 8 you can also use the Strean API:
public static int indexOf(int[] array, int valueToFind) {
if (array == null) {
return -1;
}
return IntStream.range(0, array.length)
.filter(i -> valueToFind == array[i])
.findFirst()
.orElse(-1);
}
[1]: https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#indexOf(int[],%20int)