Skip to content

Commit 09bebd5

Browse files
author
Tomasz Lelek
committed
BAEL-638 Guava Ordering
1 parent 9a16f10 commit 09bebd5

1 file changed

Lines changed: 91 additions & 0 deletions

File tree

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package org.baeldung.guava;
2+
3+
import com.google.common.base.Function;
4+
import com.google.common.collect.Ordering;
5+
import com.google.common.primitives.Ints;
6+
import org.junit.Test;
7+
8+
import java.util.Arrays;
9+
import java.util.List;
10+
11+
import static org.junit.Assert.assertEquals;
12+
13+
public class GuavaOrderingTest {
14+
@Test
15+
public void givenListOfIntegers_whenCreateNaturalOrderOrdering_shouldSortProperly() {
16+
//given
17+
List<Integer> integers = Arrays.asList(3, 2, 1);
18+
19+
//when
20+
integers.sort(Ordering.natural());
21+
22+
//then
23+
assertEquals(Arrays.asList(1, 2, 3), integers);
24+
}
25+
26+
@Test
27+
public void givenListOfPersonObject_whenSortedUsingCustomOrdering_shouldSortProperly() {
28+
//given
29+
List<Person> persons = Arrays.asList(new Person("Michael", 10), new Person("Alice", 3));
30+
Ordering<Person> orderingByName = new Ordering<Person>() {
31+
@Override
32+
public int compare(Person p1, Person p2) {
33+
return Ints.compare(p1.age, p2.age);
34+
}
35+
};
36+
37+
//when
38+
persons.sort(orderingByName);
39+
40+
//then
41+
assertEquals(Arrays.asList(new Person("Alice", 3), new Person("Michael", 10)), persons);
42+
}
43+
44+
@Test
45+
public void givenListOfPersonObject_whenSortedUsingChainedOrdering_shouldSortPropely() {
46+
//given
47+
List<Person> persons = Arrays.asList(new Person("Michael", 10), new Person("Alice", 3), new Person("Thomas", null));
48+
Ordering<Person> ordering = Ordering.natural().nullsFirst().onResultOf(new Function<Person, Comparable>() {
49+
@Override
50+
public Comparable apply(Person person) {
51+
return person.age;
52+
}
53+
});
54+
55+
//when
56+
persons.sort(ordering);
57+
58+
//then
59+
assertEquals(Arrays.asList(new Person("Thomas", null), new Person("Alice", 3), new Person("Michael", 10)), persons);
60+
}
61+
62+
63+
class Person {
64+
private final String name;
65+
private final Integer age;
66+
67+
private Person(String name, Integer age) {
68+
this.name = name;
69+
this.age = age;
70+
}
71+
72+
@Override
73+
public boolean equals(Object o) {
74+
if (this == o) return true;
75+
if (o == null || getClass() != o.getClass()) return false;
76+
77+
Person person = (Person) o;
78+
79+
if (name != null ? !name.equals(person.name) : person.name != null) return false;
80+
return age != null ? age.equals(person.age) : person.age == null;
81+
82+
}
83+
84+
@Override
85+
public int hashCode() {
86+
int result = name != null ? name.hashCode() : 0;
87+
result = 31 * result + (age != null ? age.hashCode() : 0);
88+
return result;
89+
}
90+
}
91+
}

0 commit comments

Comments
 (0)