本文介绍了Guava:如何从List和单个元素创建显式排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Guava中,给出 Collection< E> 以及类型的元素 e 我知道E 在集合中,我想创建一个自定义排序 e 首先,然后是其余的集合。然而,到达那里的方式似乎非常复杂:

In Guava, given a Collection<E> and an element e of type E that I know is in the collection, I'd like to create a custom Ordering<E> that sorts e first and then the rest of the collection. However, the way to get there seems awfully complicated:

Collection<String> values = ImmutableList.of("apples", "oranges", "pears");
String first = "oranges";

List<String> remainingValues = newArrayList(values);  // this
remainingValues.remove(first);                        // seems
Ordering<String> myOrdering =                         // very
    Ordering.explicit(first, remainingValues.toArray( // complicated!
        new String[remainingValues.size()]));         // is there an easier way?

我想要的是这样的事情:

What I'm wishing for is either something like this:

Ordering.explicit(first);

(我想这样排序第一个到开头并保留所有其他元素的顺序,但是文档说生成的Ordering将为未明确列出的元素抛出 ClassCastException 。)

(I'd like this to sort first to the beginning and retain the order of all other elements, but the docs say the resulting Ordering will throw a ClassCastException for elements not explicitly listed.)

或者像这样:

Ordering.explicit(first, values.toArray(/* etc */));

(但这会失败,因为第一个会是一个重复的值)

(But this would fail because first would be a duplicate value)

任何人都能想出一个简洁的方法来做我想做的事吗?

Can anybody come up with a concise way of doing what I want?

BTW ,它不一定是订购,它也可以是在指定中创建 Iterable 的解决方法订单,但同样,这非常复杂:

BTW, it doesn't have to be an Ordering, it could also be a workaround for creating an Iterable in the specified Order, but again, this is very complicated:

Iterable<String> sorted = Iterables.concat(
                             ImmutableList.of(first),
                             Iterables.filter(values, not(equalTo(first))));


推荐答案

嗯,这是一种方法,但是你可能找不到更好。

Well, here's one way to do it, but you may not find it much better.

final String special = "oranges";
Collections.sort(
    list,
    new Comparator<String>() {
      public int compare(String left, String right) {
        return ComparisonChain.start()
            .compareTrueFirst(left.equals(special), right.equals(special))
            .compare(left, right)
            .result();
      }
    });

- 请添加任何详细信息。

Relevant Guava feature request -- please add any details.

这篇关于Guava:如何从List和单个元素创建显式排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 10:06