How to find the index of an element in an int array?

前端 未结 19 1391
南方客
南方客 2020-11-27 02:56

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

19条回答
  •  囚心锁ツ
    2020-11-27 03:27

    In case anyone is still looking for the answer-

    1. You can use ArrayUtils.indexOf() from the [Apache Commons Library][1].

    2. 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)

提交回复
热议问题