Java- Sort Even Number First and Maintain the Order
Sort Even Number First and Maintain the Order in Java: You have an array of integers with mixed numbers i.e. even & odd, write a program in Java to sort the even numbers first then odd, and maintain the order of numbers.
Example:
int[] arr = {3, 1, 4, 2, 5, 6, 7, 8};
Output: 4 2 6 8 3 1 5 7
You can achieve this using Java 8 streams and lambda expressions. Here’s how:
SortEvenFirst.java
package org.websparrow;
import java.util.Arrays;
import java.util.Comparator;
public class SortEvenFirst {
public static void main(String[] args) {
int[] arr = {3, 1, 4, 2, 5, 6, 7, 8};
int[] sortedArr = customSort(arr);
Arrays.stream(sortedArr).forEach(num -> System.out.print(num + " "));
}
public static int[] customSort(int[] arr) {
return Arrays.stream(arr)
.boxed() // Convert int to Integer
.sorted(Comparator.comparingInt(num -> num % 2 == 0 ? 0 : 1)) // Sort even before odd
.mapToInt(Integer::intValue) // Convert Integer back to int
.toArray(); // Convert Stream to array
}
}
Output:
4 2 6 8 3 1 5 7