Guava Ordering Cookbook

1. Introduction

This cookbook illustrates how to use the Guava style Ordering and Comparators. It is continuing the cookbook and example focus format that I started in the previous post about Guava collections.

2. The Cookbook

dealing with nulls in a Collection

nulls first

List<Integer> toSort = Arrays.asList(3, 5, 4, null, 1, 2);
Collections.sort(toSort, Ordering.natural().nullsFirst());
assertThat(toSort.get(0), nullValue());

nulls last

List<Integer> toSort = Arrays.asList(3, 5, 4, null, 1, 2);
Collections.sort(toSort, Ordering.natural().nullsLast());
assertThat(toSort.get(toSort.size() - 1), nullValue());

natural ordering

List<Integer> toSort = Arrays.asList(3, 5, 4, 1, 2);
Collections.sort(toSort, Ordering.natural());

assertTrue(Ordering.natural().isOrdered(toSort));

chaining 2 orderings

List<Integer> toSort = Arrays.asList(3, 5, 4, 1, 2);
Collections.sort(toSort, Ordering.natural().reverse());

reverse an ordering

List<Integer> toSort = Arrays.asList(3, 5, 4, null, 1, 2);
Collections.sort(toSort, Ordering.natural().nullsLast().reverse());
assertThat(toSort.get(0), nullValue());

custom order – Strings by length

private class OrderingByLenght extends Ordering<String> {
    @Override
    public int compare(String s1, String s2) {
        return Ints.compare(s1.length(), s2.length());
    }
}
List<String> toSort = Arrays.asList("zz", "aa", "b", "ccc");
Ordering<String> byLength = new OrderingByLenght();
Collections.sort(toSort, byLength);

Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "zz", "aa", "ccc"));
assertTrue(expectedOrder.isOrdered(toSort))

checking explicit order

List<String> toSort = Arrays.asList("zz", "aa", "b", "ccc");
Ordering<String> byLength = new OrderingByLenght();
Collections.sort(toSort, byLength);

Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "zz", "aa", "ccc"));
assertTrue(expectedOrder.isOrdered(toSort));

checking string ordering

List<Integer> toSort = Arrays.asList(3, 5, 4, 2, 1, 2);
Collections.sort(toSort, Ordering.natural());

assertFalse(Ordering.natural().isStrictlyOrdered(toSort));

secondary ordering

List<String> toSort = Arrays.asList("zz", "aa", "b", "ccc");
Ordering<String> byLength = new OrderingByLenght();
Collections.sort(toSort, byLength.compound(Ordering.natural()));

Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "aa", "zz", "ccc"));
assertTrue(expectedOrder.isOrdered(toSort));

complex custom ordering example – with chaining

List<String> toSort = Arrays.asList("zz", "aa", null, "b", "ccc");
Collections.sort(toSort, 
    new OrderingByLenght().reverse().compound(Ordering.natural()).nullsLast());
System.out.println(toSort);

sort using toString representation

List<Integer> toSort = Arrays.asList(1, 2, 11);
Collections.sort(toSort, Ordering.usingToString());

Ordering<Integer> expectedOrder = Ordering.explicit(Lists.newArrayList(1, 11, 2));
assertTrue(expectedOrder.isOrdered(toSort));

sort, then find (binary search)

List<Integer> toSort = Arrays.asList(1, 2, 11);
Collections.sort(toSort, Ordering.usingToString());
int found = Ordering.usingToString().binarySearch(toSort, 2);
System.out.println(found);

find min/max without having to sort (faster)

List<Integer> toSort = Arrays.asList(2, 1, 11, 100, 8, 14);
int found = Ordering.usingToString().min(toSort);
assertThat(found, equalTo(1));

creating a sorted copy of the list from an ordering

List<String> toSort = Arrays.asList("aa", "b", "ccc");
List<String> sortedCopy = new OrderingByLenght().sortedCopy(toSort);

Ordering<String> expectedOrder = Ordering.explicit(Lists.newArrayList("b", "aa", "ccc"));
assertFalse(expectedOrder.isOrdered(toSort));
assertTrue(expectedOrder.isOrdered(sortedCopy));

creating a sorted partial copy – the least few elements

List<Integer> toSort = Arrays.asList(2, 1, 11, 100, 8, 14);
List<Integer> leastOf = Ordering.natural().leastOf(toSort, 3);
List<Integer> expected = Lists.newArrayList(1, 2, 8);
assertThat(expected, equalTo(leastOf));

ordering via intermediary Function

List<Integer> toSort = Arrays.asList(2, 1, 11, 100, 8, 14);
Ordering<Object> ordering = Ordering.natural().onResultOf(Functions.toStringFunction());
List<Integer> sortedCopy = ordering.sortedCopy(toSort);

List<Integer> expected = Lists.newArrayList(1, 100, 11, 14, 2, 8);
assertThat(expected, equalTo(sortedCopy));

- note: the sort logic will first run the numbers through the function – transforming them into Strings – then sort with natural ordering on the Strings

3. More Guava Cookbooks

4. Conclusion

This experimental format – the cookbook – has a clear focus – simplicity and speed, so most recipes have no additional explanation other than the code example itself.

And as I mentioned before – this as a living document – new examples and usecases are welcome in the comments, and I will continue adding my own as I run into them.

The implementation of all these examples and code snippets can be found in my Guava github project – this is an Eclipse based project, so it should be easy to import and run as it is.

I usually post about Dev stuff on Google+ - you can follow me there:

Get My 3 Spring eBooks
There’s no “one single way” to build an app. This is one way that I found works well.
×
Build Your Web App with Spring (and quickly prototype it to 90%)

,

  • Andreas Sahlbach

    just by reading I would say that the first two examples are interchanged according to their title?
    Anyway. I really like this cookbook project :-)

    • baeldung

      Nice catch – sorted. Glad you find it useful – basically I’m publishing my internal cookbooks – I’ve been keeping them for years, so why not put them out there.