在日常工作中经常用到需要对java对象集合或者Map集合中的某个属性做排序,这个需求可以利用Apache的commons-beanutils和commons-collections包来实现,主要实现方式如下:
public static <T> void sort(List<T> list, String property, boolean asc) {
Comparator<?> comparator = ComparableComparator.getInstance();
comparator = ComparatorUtils.nullLowComparator(comparator);
if (!asc) {
comparator = ComparatorUtils.reversedComparator(comparator);
}
Collections.sort(list, new BeanComparator(property, comparator));
}
下面看看一个具体实现例子,其中有按对象属性排序和Map某个key排序
首先是一个Java对象
package my.commonsstudy.beanutils;
public class User {
private String username;
private String password;
private String email;
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return this.username + ", " + this.password + ", " + this.email;
}
}
排序测试类
package my.commonsstudy.beanutils;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.ComparableComparator;
import java.util.*;
public class ComparatorTest {
public static void main(String[] args) throws Exception {
test1();
test2();
}
private static void test1() {
List<Map<String, Object>> users = new ArrayList<Map<String, Object>>();
for (int i = 0; i < 5; i++) {
Map<String, Object> user = new LinkedHashMap<String, Object>();
user.put("username", "user_" + i);
user.put("password", "passwd_" + i);
user.put("email", "user_" + i + "@localhost");
users.add(user);
}
System.out.println(users);
sort(users, "username", false);
System.out.println(users);
sort(users, "username", true);
System.out.println(users);
}
private static void test2() {
List<User> users = new ArrayList<User>();
for (int i = 0; i < 5; i++) {
users.add(new User("user_" + i, "passwd_" + i, "user_" + i + "@localhost"));
}
System.out.println(users);
sort(users, "username", false);
System.out.println(users);
sort(users, "username", true);
System.out.println(users);
}
public static <T> void sort(List<T> list, String property, boolean asc) {
Comparator<?> comparator = ComparableComparator.getInstance();
comparator = ComparatorUtils.nullLowComparator(comparator);
if (!asc) {
comparator = ComparatorUtils.reversedComparator(comparator);
}
Collections.sort(list, new BeanComparator(property, comparator));
}
}