List 排序
Java API针对集合类型的排序提供了2个方法
void java.util.Collections.sort(List<T> list)
void java.util.Collections.sort(List<T> list, Comparator<? super T> c)
如果集合里面元素都实现了Comparable
接口,则可以直接调用第一个方法排序,又称为内部排序。如果需要按照自己的想法排序,可以调用第二个方法,并传一个Comparator
进去定义排序规则。
Java针对数组也实现了排序方法,可以调用Arrays.sort
方法来排序。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class ListArraySort {
static class Book {
String name;
double price;
public Book(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public String toString() {
return name + " " + price;
}
}
static class Person implements Comparable<Person> {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Person o) {
// 按照年龄升序排列
return this.getAge() - o.getAge();
}
public String toString() {
return name + " " + age;
}
}
public static void main(String[] args) {
testInnerSort();
testOuterSort();
testArraySort();
}
public static void testInnerSort() {
List<Person> listA = new ArrayList<Person>();
listA.add(new Person("Messi", 32));
listA.add(new Person("Neymar", 27));
java.util.Collections.sort(listA);
for (Person person : listA) {
System.out.println(person);
}
}
public static void testOuterSort() {
List<Book> listB = new ArrayList<>();
listB.add(new Book("Data Structures and Algorithm Analysis in C", 23.7));
listB.add(new Book("Introduction to Algorithm", 35));
java.util.Collections.sort(listB, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
// 按照书名降序排列
return o2.getName().compareTo(o1.getName());
}
});
for (Book book : listB) {
System.out.println(book);
}
}
public static void testArraySort() {
Integer[] array = new Integer[] {5, 4, 6, 3, 2, 8, 9, 12, 3};
Arrays.sort(array, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// 降序排列
return o2 - o1;
}
});
System.out.println(Arrays.asList(array));
}
}
输出
Neymar 27
Messi 32
Introduction to Algorithm 35.0
Data Structures and Algorithm Analysis in C 23.7
[12, 9, 8, 6, 5, 4, 3, 3, 2]
网友评论