Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava: How to create an explicit Ordering from a List and a single element?

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);

(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.)

Or like this:

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, 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))));
like image 806
Sean Patrick Floyd Avatar asked Jan 18 '13 16:01

Sean Patrick Floyd


1 Answers

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();
      }
    });

ComparisonChain docs

Relevant Guava feature request -- please add any details.

like image 178
Kevin Bourrillion Avatar answered Nov 16 '22 03:11

Kevin Bourrillion