在 Java8 的 stream 之前,将对象进行排序的时候,可能需要对象实现 Comparable 接口,或者自己实现一个 Comparator,
比如这样子
我的对象是 Entity
public class Entity {
private Long id;
private Long sortValue;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Long getSortValue() { return sortValue; }
public void setSortValue(Long sortValue) { this.sortValue = sortValue; }}
复制代码
Comparator
public class MyComparator implements Comparator { @Override public int compare(Object o1, Object o2) { Entity e1 = (Entity) o1; Entity e2 = (Entity) o2; if (e1.getSortValue() < e2.getSortValue()) { return -1; } else if (e1.getSortValue().equals(e2.getSortValue())) { return 0; } else { return 1; } }}
复制代码
比较代码
private static MyComparator myComparator = new MyComparator();
public static void main(String[] args) { List<Entity> list = new ArrayList<Entity>(); Entity e1 = new Entity(); e1.setId(1L); e1.setSortValue(1L); list.add(e1); Entity e2 = new Entity(); e2.setId(2L); e2.setSortValue(null); list.add(e2); Collections.sort(list, myComparator);
复制代码
看到这里的 e2 的排序值是 null,在 Comparator 中如果要正常运行的话,就得判空之类的,这里有两点需要,一个是不想写这个 MyComparator,然后也没那么好排除掉 list 里排序值,那么有什么办法能解决这种问题呢,应该说 java 的这方面真的是很强大
看一下 nullsFirst 的实现
final static class NullComparator<T> implements Comparator<T>, Serializable { private static final long serialVersionUID = -7569533591570686392L; private final boolean nullFirst; // if null, non-null Ts are considered equal private final Comparator<T> real;
@SuppressWarnings("unchecked") NullComparator(boolean nullFirst, Comparator<? super T> real) { this.nullFirst = nullFirst; this.real = (Comparator<T>) real; }
@Override public int compare(T a, T b) { if (a == null) { return (b == null) ? 0 : (nullFirst ? -1 : 1); } else if (b == null) { return nullFirst ? 1: -1; } else { return (real == null) ? 0 : real.compare(a, b); } }
复制代码
核心代码就是下面这段,其实就是帮我们把前面要做的事情做掉了,是不是挺方便的。
本文使用署名 4.0 国际 (CC BY 4.0)许可协议,欢迎转载、或重新修改使用,但需要注明来源。
本文作者: Nicksxs
创建时间: 2020-04-05
本文链接: Java 中的Comparator使用技巧
评论