guava examples for ordering
This commit is contained in:
parent
83f2c36c0e
commit
8c81ec9e42
|
@ -1,5 +1,6 @@
|
||||||
package org.baeldung.guava.collections;
|
package org.baeldung.guava.collections;
|
||||||
|
|
||||||
|
import static org.hamcrest.Matchers.equalTo;
|
||||||
import static org.hamcrest.Matchers.nullValue;
|
import static org.hamcrest.Matchers.nullValue;
|
||||||
import static org.junit.Assert.assertThat;
|
import static org.junit.Assert.assertThat;
|
||||||
|
|
||||||
|
@ -10,6 +11,7 @@ import java.util.List;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import com.google.common.collect.Ordering;
|
import com.google.common.collect.Ordering;
|
||||||
|
import com.google.common.primitives.Ints;
|
||||||
|
|
||||||
public class GuavaOrderingExamplesTest {
|
public class GuavaOrderingExamplesTest {
|
||||||
|
|
||||||
|
@ -35,4 +37,20 @@ public class GuavaOrderingExamplesTest {
|
||||||
Collections.sort(nums, Ordering.natural().nullsLast().reverse());
|
Collections.sort(nums, Ordering.natural().nullsLast().reverse());
|
||||||
assertThat(nums.get(0), nullValue());
|
assertThat(nums.get(0), nullValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public final void whenSortingCollectionsOfStringsByLenght_thenCorrectlySorted() {
|
||||||
|
final List<String> toSort = Arrays.asList("aa", "b", null, "ccc");
|
||||||
|
final Ordering<String> byLength = new Ordering<String>() {
|
||||||
|
@Override
|
||||||
|
public int compare(final String s1, final String s2) {
|
||||||
|
return Ints.compare(s1.length(), s2.length());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Collections.sort(toSort, byLength.nullsFirst());
|
||||||
|
assertThat(toSort.get(0), nullValue());
|
||||||
|
assertThat(toSort.get(1), equalTo("b"));
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue