Find the First Odd Number from a List in Java

Problem:
Using Java 8 Streams, how do you find the first odd number in a list efficiently, without manually looping?

✅ Example:

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class FirstOddNumber {

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(2, 4, 6, 8, 17, 9, 24, 19);

        Optional<Integer> firstOdd = numbers.stream()  // Use stream(), parallelStream() is not necessary here
                .filter(element -> element % 2 != 0)  // Filter odd numbers
                .findFirst();  // Find the first matching element

        firstOdd.ifPresent(System.out::println);
    }
}

✅ Output:

17

✅ ✅ Explanation:

  1. We create a list of numbers: [2, 4, 6, 8, 17, 9, 24, 19]
  2. We use .stream() (sequential stream is sufficient for this purpose): numbers.stream()
  3. .filter(ele -> ele % 2 != 0) filters all odd numbers:
    • Result after filtering: [17, 9, 19].
  4. .findFirst() returns the first element in encounter order, wrapped in Optional<Integer>.
  5. We print the result using: firstOdd.ifPresent(System.out::println);

✅ Important Note:

  • Avoid using .parallelStream() here because it may not guarantee order in finding the first element.
    Always prefer .stream() when order matters.

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *