ordering examples
This commit is contained in:
parent
b19a5af156
commit
2a5442477d
|
@ -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<Integer> 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<Integer> 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<String> 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<String> 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<String> toSort = Arrays.asList("aa", "b", "ccc");
|
||||
final List<String> sortedCopy = new OrderingByLenght().sortedCopy(toSort);
|
||||
|
||||
final Ordering<String> 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<Integer> toSort = Arrays.asList(1, 2, 11);
|
||||
Collections.sort(toSort, Ordering.usingToString());
|
||||
|
||||
final Ordering<Integer> expectedOrder = Ordering.explicit(Lists.newArrayList(1, 11, 2));
|
||||
assertTrue(expectedOrder.isOrdered(toSort));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue