11package org .baeldung .guava .collections ;
22
33import static org .hamcrest .Matchers .nullValue ;
4+ import static org .junit .Assert .assertFalse ;
45import static org .junit .Assert .assertThat ;
56import static org .junit .Assert .assertTrue ;
67
@@ -25,6 +26,8 @@ public final int compare(final String s1, final String s2) {
2526
2627 // tests
2728
29+ // dealing with null
30+
2831 @ Test
2932 public final void givenCollectionWithNulls_whenSortingWithNullsLast_thenNullsAreLast () {
3033 final List <Integer > toSort = Arrays .asList (3 , 5 , 4 , null , 1 , 2 );
@@ -46,6 +49,18 @@ public final void whenCollectionIsSortedNullsLastReversed_thenNullAreFirst() {
4649 assertThat (toSort .get (0 ), nullValue ());
4750 }
4851
52+ // natural ordering
53+
54+ @ Test
55+ public final void whenSortingWithNaturalOrdering_thenCorectlySorted () {
56+ final List <Integer > toSort = Arrays .asList (3 , 5 , 4 , 1 , 2 );
57+ Collections .sort (toSort , Ordering .natural ());
58+
59+ assertTrue (Ordering .natural ().isOrdered (toSort ));
60+ }
61+
62+ // custom - by length
63+
4964 @ Test
5065 public final void givenCollectionIsSorted_whenUsingOrderingApiToCheckOrder_thenCheckCanBePerformed () {
5166 final List <String > toSort = Arrays .asList ("zz" , "aa" , "b" , "ccc" );
@@ -78,4 +93,35 @@ public final void whenSortingCollectionsOfStringsByLenghtWithSecondaryNaturalOrd
7893 assertTrue (expectedOrder .isOrdered (toSort ));
7994 }
8095
96+ @ Test
97+ public final void whenSortingCollectionsWithComplexOrderingExample_thenCorrectlySorted () {
98+ final List <String > toSort = Arrays .asList ("zz" , "aa" , null , "b" , "ccc" );
99+
100+ Collections .sort (toSort , new OrderingByLenght ().reverse ().compound (Ordering .natural ()).nullsLast ());
101+ System .out .println (toSort );
102+ }
103+
104+ // sorted copy
105+
106+ @ Test
107+ public final void givenUnorderdList_whenRetrievingSortedCopy_thenSorted () {
108+ final List <String > toSort = Arrays .asList ("aa" , "b" , "ccc" );
109+ final List <String > sortedCopy = new OrderingByLenght ().sortedCopy (toSort );
110+
111+ final Ordering <String > expectedOrder = Ordering .explicit (Lists .newArrayList ("b" , "aa" , "ccc" ));
112+ assertFalse (expectedOrder .isOrdered (toSort ));
113+ assertTrue (expectedOrder .isOrdered (sortedCopy ));
114+ }
115+
116+ // to string
117+
118+ @ Test
119+ public final void givenUnorderdList_whenUsingToStringForSortingObjects_thenSortedWithToString () {
120+ final List <Integer > toSort = Arrays .asList (1 , 2 , 11 );
121+ Collections .sort (toSort , Ordering .usingToString ());
122+
123+ final Ordering <Integer > expectedOrder = Ordering .explicit (Lists .newArrayList (1 , 11 , 2 ));
124+ assertTrue (expectedOrder .isOrdered (toSort ));
125+ }
126+
81127}
0 commit comments