使用Comparator接口与Lambda表达式排序int数组遇编译错误求助
Hey, let's break down what's going on here and fix your code!
The core issue you're hitting is that the Arrays.sort overload that takes a Comparator only works with object arrays (like Integer[]), not primitive type arrays (like int[]). The compiler error spells this out clearly when it mentions equality constraints: int and upper bounds: Object — since Comparator operates on types that inherit from Object, the primitive int can't be used with this method.
Solution 1: Use Integer[] with Lambda + Comparator
If you specifically want to use a Lambda expression to define sorting logic, convert your primitive int[] to an Integer[] (boxed object array) first, sort it, then convert back if you need the primitive type:
import java.util.Arrays; public class MyClass{ public static void main(String args[]) { int[] arr = {5,3,7,8,1,4,6,9}; // Convert primitive int array to Integer object array Integer[] integerArr = Arrays.stream(arr).boxed().toArray(Integer[]::new); // Sort using Lambda as Comparator (ascending order here) Arrays.sort(integerArr, (o1, o2) -> o1 - o2); // Convert back to int array if needed int[] sortedArr = Arrays.stream(integerArr).mapToInt(Integer::intValue).toArray(); System.out.println(Arrays.toString(sortedArr)); } }
Solution 2: Use the default Arrays.sort(int[]) for simple ascending sort
If you just need a standard ascending sort, you don't need a Comparator at all! The default Arrays.sort(int[]) method is built specifically for primitive integer arrays and does exactly what you want:
import java.util.Arrays; public class MyClass{ public static void main(String args[]) { int[] arr = {5,3,7,8,1,4,6,9}; Arrays.sort(arr); // Default ascending sort for primitive int array System.out.println(Arrays.toString(arr)); } }
Bonus: Custom sort (e.g., descending order) for primitive arrays
If you need a custom order like descending, you can use streams to handle boxing and sorting in one chain:
import java.util.Arrays; public class MyClass{ public static void main(String args[]) { int[] arr = {5,3,7,8,1,4,6,9}; int[] sortedDescArr = Arrays.stream(arr) .boxed() .sorted((o1, o2) -> o2 - o1) // Descending order .mapToInt(Integer::intValue) .toArray(); System.out.println(Arrays.toString(sortedDescArr)); } }
内容的提问来源于stack exchange,提问作者Harsh Shah

