java ArrayList資料物件按排序值大小排序
阿新 • • 發佈:2019-01-09
QQ群:372135639
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
/**
*
* @author www.zuidaima.com
*
*/
public class ListSort {
public static void main(String[] args) {
List<User> users = new ArrayList<User>();
int id = 0;
User user = null;
Random random = new Random();
id = random.nextInt(100000);
user = new User(id);
user.setId(id);
users.add(user);
id = random.nextInt(100000);
user = new User(id);
user.setId(id);
users.add(user);
id = random.nextInt(100000 );
user = new User(id);
user.setId(id);
users.add(user);
id = random.nextInt(100000);
user = new User(id);
user.setId(id);
users.add(user);
id = random.nextInt(100000);
user = new User(id);
user.setId(id);
users.add(user);
id = random.nextInt(100000 );
user = new User(id);
user.setId(id);
users.add(user);
id = random.nextInt(100000);
user = new User(id);
user.setId(id);
users.add(user);
id = random.nextInt(100000);
user = new User(id);
user.setId(id);
users.add(user);
id = random.nextInt(100000);
user = new User(id);
user.setId(id);
users.add(user);
System.out.println("Before sort:");
for (User _user : users) {
System.out.print(_user + " ");
}
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User user1, User user2) {
Integer id1 = user1.getId();
Integer id2 = user2.getId();
//可以按User物件的其他屬性排序,只要屬性支援compareTo方法
return id2.compareTo(id1);
}
});
System.out.println("\nAfter sort 從大到小倒序:");
for (User _user : users) {
System.out.print(_user + " ");
}
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User user1, User user2) {
Integer id1 = user1.getId();
Integer id2 = user2.getId();
//可以按User物件的其他屬性排序,只要屬性支援compareTo方法
return id1.compareTo(id2);
}
});
System.out.println("\nAfter sort 從小到大正序:");
for (User _user : users) {
System.out.print(_user + " ");
}
}
}
class User {
private int id;
public User(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return id + "";
}
}
程式執行輸出結果:
Before sort:
49459 73363 18294 65350 36522 77535 38273 58512 34980
After sort 倒序:
77535 73363 65350 58512 49459 38273 36522 34980 18294
After sort 正序:
18294 34980 36522 38273 49459 58512 65350 73363 77535