最经常使用的Java Sort Utils

通用工具类Utils

java.util、Guava、Apache Commons中提供了不少有用的工具类,可提高开发效率;
注意:import org.assertj.core.internal中提供的工具类在Jenkins构建中存在问题,尽可能避免使用。java

import java.util.Arrays;
import java.util.Collections;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
排序Sort工具类
int[] array = {9,9,6,11,7,24,7};
Arrays.sort(array);

Collections.sort(Lists.newArrayList(new User(7),new User(8),new User(6)));

// TreeMap的实现相似TreeSet
TreeSet<User> users = new TreeSet<>(new java.util.Comparator<User>() {
	@Override
	public int compare(User user1, User user2) {
		return user1.getAge() - user2.getAge();
	}
});
users.add(new User(77));
users.add(new User(88));
users.add(new User(66));
System.out.println(users);
Comparable和Comparator
  • Comparable至关因而内部比较器,Comparator至关因而外部比较器
  • Comparator接口的实现方式是种典型的策略模式
  • 实现Comparator接口须要实现compare(T o1,T o2)函数,但能够不实现equals(Object obj)函数
  • compare(T o1,T o2)是比较o1和o2的大小,返回负数意味着o1比o2小,返回零意味着o1等于o2;返回正数意味着o1大于o2
  • 若是类没有实现Comparable接口,或者实现了Comparable接口,可是对compareTo的实现算法不满意,那么能够实现Comparator接口来自定义比较器
  • 实现Comparable接口的方式比实现Comparator接口的耦合性要强一些,若是要修改比较算法,要修改Comparable接口的实现类,而实现Comparator的类是在外部进行比较的,不须要对实现类有任何修改
/** * 根据文件的修改日期排序 * * @param fliePath */
public static void orderByDate(String fliePath) {
	File file = new File(fliePath);
	File[] files = file.listFiles();
	Arrays.sort(files, new Comparator<File>() {
		public int compare(File file1, File file2) {
			long diff = file1.lastModified() - file2.lastModified();
			if (diff > 0)
				return 1;
			else if (diff == 0)
				return 0;
			else
				return -1;
		}

		public boolean equals(Object obj) {
			return true;
		}

	});
	for (int i = files.length - 1; i > -1; i--) {
		System.out.println(files[i].getName() + ":" + new Date(files[i].lastModified()));
	}
}

public class User implements Comparable<User> {

	private int age;

	@Override
	public int compareTo(User user) {
		if (this.age > user.getAge()) {
			return 1;
		} else if (this.age < user.getAge()) {
			return -1;
		} else {
			return 0;
		}
	}
    // get,set,constructor,toString略
}
Collections.sort(Lists.newArrayList(new User(7),new User(8),new User(6)));

备注

  • 针对大数据量,或者须要更高的性能,须要自定义实现对应的排序算法。