Java sort用法详解(二维数组排序,List<>排序,lambada表达式,自定义类型排序)
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortExample {
// 二维数组按照第一列排序
public static void sort2DArray(int[][] array) {
Arrays.sort(array, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o1[0], o2[0]);
}
});
}
// List按照自定义规则排序
public static void sortListWithLambda(List<String> list) {
list.sort((s1, s2) -> s1.compareTo(s2));
}
// List按照对象属性排序
public static <T> void sortListByObjectProperty(List<T> list, final String propertyName) {
list.sort(new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
try {
// 使用反射获取属性值
java.lang.reflect.Field field = o1.getClass().getDeclaredField(propertyName);
field.setAccessible(true);
Object val1 = field.get(o1);
Object val2 = field.get(o2);
return ((Comparable) val1).compareTo(val2);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
});
}
public static void main(String[] args) {
// 二维数组排序示例
int[][] array = {{2, 1}, {4, 3}, {1, 2}};
sort2DArray(array);
System.out.println(Arrays.deepToString(array));
// List排序示例
List<String> strings = Arrays.asList("banana", "apple", "cherry");
sortListWithLambda(strings);
System.out.println(strings);
// 对象列表排序示例
List<Person> people = Arrays.asList(new Person("John", 30), new Person("Alice", 25));
sortListByObjectProperty(people, "age");
System.out.println(people.stream().map(p -> p.getName() + ": " + p.getAge()).collect(Collectors.toList()));
}
static class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
这个代码示例展示了如何使用Java的Arrays.sort
评论已关闭