From 2a5442477d18e68f386477d73ef1a4881816c9a1 Mon Sep 17 00:00:00 2001 From: Eugen Paraschiv Date: Fri, 25 Oct 2013 12:41:23 +0300 Subject: [PATCH] ordering examples --- .../GuavaOrderingExamplesTest.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/guava/src/test/java/org/baeldung/guava/collections/GuavaOrderingExamplesTest.java b/guava/src/test/java/org/baeldung/guava/collections/GuavaOrderingExamplesTest.java index a7e88fb90c..b96f751e46 100644 --- a/guava/src/test/java/org/baeldung/guava/collections/GuavaOrderingExamplesTest.java +++ b/guava/src/test/java/org/baeldung/guava/collections/GuavaOrderingExamplesTest.java @@ -1,6 +1,7 @@ package org.baeldung.guava.collections; import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; @@ -25,6 +26,8 @@ public class GuavaOrderingExamplesTest { // tests + // dealing with null + @Test public final void givenCollectionWithNulls_whenSortingWithNullsLast_thenNullsAreLast() { final List toSort = Arrays.asList(3, 5, 4, null, 1, 2); @@ -46,6 +49,18 @@ public class GuavaOrderingExamplesTest { assertThat(toSort.get(0), nullValue()); } + // natural ordering + + @Test + public final void whenSortingWithNaturalOrdering_thenCorectlySorted() { + final List toSort = Arrays.asList(3, 5, 4, 1, 2); + Collections.sort(toSort, Ordering.natural()); + + assertTrue(Ordering.natural().isOrdered(toSort)); + } + + // custom - by length + @Test public final void givenCollectionIsSorted_whenUsingOrderingApiToCheckOrder_thenCheckCanBePerformed() { final List toSort = Arrays.asList("zz", "aa", "b", "ccc"); @@ -78,4 +93,35 @@ public class GuavaOrderingExamplesTest { assertTrue(expectedOrder.isOrdered(toSort)); } + @Test + public final void whenSortingCollectionsWithComplexOrderingExample_thenCorrectlySorted() { + final List toSort = Arrays.asList("zz", "aa", null, "b", "ccc"); + + Collections.sort(toSort, new OrderingByLenght().reverse().compound(Ordering.natural()).nullsLast()); + System.out.println(toSort); + } + + // sorted copy + + @Test + public final void givenUnorderdList_whenRetrievingSortedCopy_thenSorted() { + final List toSort = Arrays.asList("aa", "b", "ccc"); + final List sortedCopy = new OrderingByLenght().sortedCopy(toSort); + + final Ordering expectedOrder = Ordering.explicit(Lists.newArrayList("b", "aa", "ccc")); + assertFalse(expectedOrder.isOrdered(toSort)); + assertTrue(expectedOrder.isOrdered(sortedCopy)); + } + + // to string + + @Test + public final void givenUnorderdList_whenUsingToStringForSortingObjects_thenSortedWithToString() { + final List toSort = Arrays.asList(1, 2, 11); + Collections.sort(toSort, Ordering.usingToString()); + + final Ordering expectedOrder = Ordering.explicit(Lists.newArrayList(1, 11, 2)); + assertTrue(expectedOrder.isOrdered(toSort)); + } + }