OneCompiler

[Java] How to find the first element of an array with a condition?

I want to find first element of an array with a condition, how can I do that in Java?

1 Answer

4 years ago by

Using streams we can filter the array first then find the index at position of 0 to find the first element. Following code shows that.

In this example I am using even numbers as condition to demonstrate

import java.util.Arrays;

public class JavaArrays {
	public static void main(String[] args) {
		int[] numbers = { 45, 22, 67, 90 };

		System.out.println(Arrays
							.stream(numbers)
							.filter(ele -> ele % 2 == 0)
							.findFirst());

	}
}

Note: The return type is OptionalInt, if you want an int you can do .getAsInt() but you will get an exception if the array is empty.

try online here: https://onecompiler.com/java/3xmswbn5t

4 years ago by Karthik Divi