java list集合使用Collections中的sort方法进行排序(Comparator),超实用

时间:2021-01-03 02:52:11

在java中有没有遇到对list集合进行排序,其实很简单的,需要集合类Collections中sort方法

public static <T> void sort(List<T> list, Comparator<? super T> c) {
Object[] a = list.toArray();
Arrays.sort(a, (Comparator)c);
ListIterator i = list.listIterator();
for (int j=0; j<a.length; j++) {
i.next();
i.set(a[j]);
}
}

使用方法及代码实现:

package collections.sort;

import java.util.Date;


public class Book {
private Long id;
private Date time;
private String name;

public Book(Long id, Date time, String name) {
super();
this.id = id;
this.time = time;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

package collections.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class TestSort {
public static void main(String[] args) {
List<Book> books = new ArrayList<>();
books.add(new Book(5l, subDate(0), "zjq5"));
books.add(new Book(2l, subDate(3), "zjq2"));
books.add(new Book(3l, subDate(2), "zjq3"));
books.add(new Book(1l, subDate(4), "zjq1"));
books.add(new Book(4l, subDate(1), "zjq4"));
Collections.sort(books, new Comparator<Book>() {

@Override
public int compare(Book o1, Book o2) {
//o1和o2反过来决定升序和降序
// return o1.getId().compareTo(o2.getId());升序
// return o2.getId().compareTo(o1.getId());降序
// return o1.getName().compareTo(o2.getName());
// return o2.getName().compareTo(o1.getName());
// return o1.getTime().compareTo(o2.getTime());
return o2.getTime().compareTo(o1.getTime());
}

});
for (Book book : books) {
System.out.println(book.getId());
}
}

//日期减一天 加一天
public static Date subDate(int sum){
return new Date(new Date().getTime()-sum*24*60*60*1000);
}
}