Java stream - filter a list of odd/even numbers

PROBLEM

You’re writing a Java program and wish to filter out a list of integer numbers. Given a list of integers, you want to have a new list having only odd numbers.

solution

Use the stream API and the filter method. Let’s suppose the following list:

				
					List<Integer> numbers = Arrays.asList(2,3,4,1,0,-2,-45,-70,80,99,45,87,33,91,22,16,73,40,93);
				
			

We would like to filter the numbers and get the odd numbers only. We know that odd numbers are not divisible by 2 so we will use that logic for filtering. In Java the remainder of a division is the %, so a number is odd when

				
					number % 2 == 1
				
			

Putting it into the filter lambda method:

				
					List<Integer> oddNumbers = numbers.stream()
        .filter(number -> number % 2 == 1)
        .collect(Collectors.toList());
				
			

Running it inside a main method and printing the result:

				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class OddNumbers {

    public static void main(String[] args) {

        List<Integer> numbers = Arrays.asList(2,3,4,1,0,-2,-45,-70,80,99,45,87,33,91,22,16,73,40,93);

        List<Integer> oddNumbers = numbers.stream()
                .filter(number -> number % 2 == 1)
                .collect(Collectors.toList());

        System.out.println(oddNumbers);
    }
}
				
			

output - odd numbers

				
					[3,1,99,45,87,33,91,73,93]
				
			

Looks correct.

If we wanted to get the even numbers, simply we change the logic inside filter to check for 0 instead of 1

				
					number % 2 == 0
				
			
				
					List<Integer> evenNumbers = numbers.stream()
        .filter(number -> number % 2 == 0)
        .collect(Collectors.toList());
				
			

output - even numbers

				
					[2,4,0,-2,-70,80,22,16,40]
				
			

conclusion

In this post, we saw how to simply filter a list of integer numbers to get only the even/ odd ones. You can check the full documentation of the Stream API.

More Java Posts

Share it!

Facebook
Twitter
LinkedIn
Reddit
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x