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;
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);
/** * 根据文件的修改日期排序 * * @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)));