Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through array - java

Tags:

java

arrays

I was wondering if it was better to have a method for this and pass the Array to that method or to write it out every time I want to check if a number is in the array.

For example:

public static boolean inArray(int[] array, int check) {      for (int i = 0; i < array.length; i++) {         if (array[i] == check)              return true;     }      return false; } 

Thanks for the help in advance!

like image 220
Eli Avatar asked Jan 23 '13 21:01

Eli


People also ask

How do I loop through an array in Java?

Iterating over an array You can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.

How do you loop over an array?

How to Loop Through an Array with a forEach Loop in JavaScript. The array method forEach() loop's through any array, executing a provided function once for each array element in ascending index order. This function is known as a callback function.

Can we use iterator in array?

The most common iterator in JavaScript is the Array iterator, which returns each value in the associated array in sequence. While it is easy to imagine that all iterators could be expressed as arrays, this is not true. Arrays must be allocated in their entirety, but iterators are consumed only as necessary.

Can we use forEach for array in Java?

ArrayList forEach() method in JavaThe forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised.


1 Answers

Since atleast Java 1.5.0 (Java 5) the code can be cleaned up a bit. Arrays and anything that implements Iterator (e.g. Collections) can be looped as such:

public static boolean inArray(int[] array, int check) {    for (int o : array){       if (o == check) {          return true;       }    }    return false; } 

In Java 8 you can also do something like:

// import java.util.stream.IntStream;  public static boolean inArray(int[] array, int check) {    return IntStream.of(array).anyMatch(val -> val == check); } 

Although converting to a stream for this is probably overkill.

like image 196
Philip Whitehouse Avatar answered Sep 18 '22 19:09

Philip Whitehouse