java-自定义比较器

给出以下列表:“ A”,“ B”,“ C”,“ D”,“ E”,“ F”,“ G”

我需要执行以下排序的比较器:

>指定某个元素(例如“ D”)
>从元素开始
>,然后按原始顺序排列原始列表中的所有以下元素
>后跟原始顺序中原始列表的所有先前元素

结果将是:“ D”,“ E”,“ F”,“ G”,“ A”,“ B”,“ C”

请注意,我知道我可以做类似以下的事情:

List<String> following = myList.subList(myList.indexOf("D") + 1, myList.size());
List<String> preceding = myList.subList(0, myList.indexOf("D"));
List<String> newList = Stream.of(Collections.singletonList("D"), following, preceding)
                       .flatMap(List::stream)
                       .collect(Collectors.toList());

在这个问题上,我明确地表示比较器实现.

显然,它必须具有列表&元素作为参数,我只是不清楚比较算法本身:

private static class MyComparator<T> implements Comparator<T> {

  private final List<T> list;
  private final T element;

  private MyComparator(List<T> list, T element) {
    this.list = list;
    this.element = element;
  }

  @Override
  public int compare(T o1, T o2) {
    // Not clear
  }
}

解决方法:

我想这就是你想要的:

class ImposedOrder<T> implements Comparator<T> {

    private final List<T> list;
    private final int startIndex;

    ImposedOrder(List<T> list, T startElement) {
        this.list = new ArrayList<>(list);
        this.startIndex = list.indexOf(startElement);
        if (startIndex < 0) {
            throw new IllegalArgumentException();
        }
    }

    @Override
    public int compare(T t1, T t2) {
        int t1Index = list.indexOf(t1);
        int t2Index = list.indexOf(t2);
        return Integer.compare(adjust(t1Index), adjust(t2Index));
    }

    private int adjust(int rawIndex) {
        if (rawIndex >= startIndex) {
            return rawIndex;
        }
        return rawIndex + list.size();
    }
}

一些额外的验证可能是为了避免强加重复的订单清单.

使用indexOf进行的线性搜索不会给您带来出色的性能,但是对于一个小的订单列表来说就足够了.否则,可以在比较器的构造函数中将元素映射到其调整后的索引,而不是保存施加的订单列表的副本.

像这样 :

class ImposedOrder<T> implements Comparator<T> {

    private final Map<T, Integer> map;
    private final int startIndex;

    ImposedOrder(List<T> list, T startElement) {
        this.startIndex = list.indexOf(startElement);
        if (startIndex < 0) {
            throw new IllegalArgumentException();
        }
        this.map = IntStream.range(0, list.size())
                .boxed()
                .collect(Collectors.toMap(
                        list::get,
                        i -> adjust(startIndex, list.size(), i)
                ));
    }

    @Override
    public int compare(T t1, T t2) {
        Integer t1Index = map.get(t1);
        Integer t2Index = map.get(t2);
        return t1Index.compareTo(t2Index);
    }

    private static int adjust(int startIndex, int size, int rawIndex) {
        if (rawIndex >= startIndex) {
            return rawIndex;
        }
        return rawIndex + size;
    }
}
上一篇:Java 8 Comparator keyExtractor


下一篇:Comparator接口和 Comparator接口