Sort even and odd numbers in ascending & descending order in Java


To sort even and odd numbers in ascending and descending order in Java, you can utilize Java 8 features and leverage Streams to perform the sorting of even and odd numbers more succinctly.

1. Even numbers in ascending order

nums.stream()
        .filter(e -> e % 2 == 0)
        .sorted(Comparator.naturalOrder())
        .forEach(System.out::println);

2. Even numbers in descending order

nums.stream()
        .filter(e -> e % 2 == 0)
        .sorted(Comparator.reverseOrder())
        .forEach(System.out::println);

3. Even numbers in ascending order

nums.stream()
        .filter(e -> e % 2 != 0)
        .sorted(Comparator.naturalOrder())
        .forEach(System.out::println);

4. Even numbers in descending order

nums.stream()
        .filter(e -> e % 2 != 0)
        .sorted(Comparator.reverseOrder())
        .forEach(System.out::println);

Here’s the complete Java code to achieve this:

SortEvenOddInOrder.java
package org.websparrow.interview;

import java.util.Comparator;
import java.util.List;

public class SortEvenOddInOrder {

    public static void main(String[] args) {

        List<Integer> nums = List.of(10, 43, 2, 5, 1, 7, 4, 55, 22, 60);

        System.out.println("# Even numbers in ascending order ***********");
        nums.stream()
                .filter(e -> e % 2 == 0)
                .sorted(Comparator.naturalOrder())
                .forEach(System.out::println);

        System.out.println("# Even numbers in descending order ***********");
        nums.stream()
                .filter(e -> e % 2 == 0)
                .sorted(Comparator.reverseOrder())
                .forEach(System.out::println);

        System.out.println("# Odd numbers in ascending order ***********");
        nums.stream()
                .filter(e -> e % 2 != 0)
                .sorted(Comparator.naturalOrder())
                .forEach(System.out::println);

        System.out.println("# Odd numbers in descending order ***********");
        nums.stream()
                .filter(e -> e % 2 != 0)
                .sorted(Comparator.reverseOrder())
                .forEach(System.out::println);
    }
}

Output:

console.log
# Even numbers in ascending order ***********
2
4
10
22
60
# Even numbers in descending order ***********
60
22
10
4
2
# Odd numbers in ascending order ***********
1
5
7
43
55
# Odd numbers in descending order ***********
55
43
7
5
1

References

  1. Java- Sort Even Number First and Maintain the Order
  2. How to sort Map by Key or Value in Java 8
  3. How to sort list in Java 8

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.