Learnitweb

Java program to find first even integer in list of numbers

We’ll see two approaches to get the first even number from a list of numbers. In the first approach, we iterate the list and return the first even number. We’ll use the for loop to iterate the list.

In the second approach, we’ll use the Java stream and findFirst() method to get the first even number.

Approach 1: By iterating the list using for loop

In the first approach, we iterate the list using for loop. We check each element if it is even or not. When found, we return the number.

import java.util.ArrayList;
import java.util.List;

public class FirstEvenExample {

	public static void main(String[] args) {
		List<Integer> list = new ArrayList();
		list.add(1);
		list.add(3);
		list.add(5);
		list.add(7);
		list.add(8);
		list.add(7);
		Integer result = getFirstEven(list);
		if (result != null) {
			System.out.println("First even number is: " + result);
		} else {
			System.out.println("No even number found");
		}

	}

	static Integer getFirstEven(List<Integer> list) {
		Integer result = null;
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i) % 2 == 0) {
				result = list.get(i);
				break;
			}
		}
		return result;
	}
}

Output

First even number is: 8

Approach 2: Using Java stream and findFirst() method

In this approach, we convert the list to stream. Then we use filter() to filter out the even elements. In the end we use findFirst() method to get the first even number.

import java.util.ArrayList;
import java.util.List;

public class FirstEvenExample {

	public static void main(String[] args) {
		List<Integer> list = new ArrayList();
		list.add(1);
		list.add(3);
		list.add(5);
		list.add(7);
		list.add(8);
		list.add(7);
		Integer result = getFirstEven(list);
		if (result != null) {
			System.out.println("First even number is: " + result);
		} else {
			System.out.println("No even number found");
		}

	}

	static Integer getFirstEven(List<Integer> list) {
		return list.stream().filter(i -> i % 2 == 0).findFirst().orElse(null);
	}
}