forked from gmjonker/util
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsSortedByMatcher.java
More file actions
54 lines (46 loc) · 1.61 KB
/
IsSortedByMatcher.java
File metadata and controls
54 lines (46 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package gmjonker.matchers;
import com.google.common.collect.Ordering;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.TypeSafeMatcher;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
public class IsSortedByMatcher<T, U extends Comparable<U>> extends TypeSafeMatcher<List<T>>
{
private final Function<T, U> mapper;
private final boolean reverse;
public IsSortedByMatcher(Function<T, U> mapper, boolean reverse)
{
this.mapper = mapper;
this.reverse = reverse;
}
@Override
public boolean matchesSafely(List<T> list)
{
if (reverse) {
Comparator<T> comparator = (t1, t2) -> mapper.apply(t1).compareTo(mapper.apply(t2));
return Ordering.from(comparator).reverse().isOrdered(list);
} else {
Comparator<T> comparator = (t1, t2) -> mapper.apply(t1).compareTo(mapper.apply(t2));
return Ordering.from(comparator).isOrdered(list);
}
}
public void describeTo(Description description)
{
if (reverse)
description.appendText("a reverse-sorted list after mapping" );
else
description.appendText("a sorted list after mapping");
}
@Factory
public static <S, U extends Comparable<U>> IsSortedByMatcher<S,U> isSortedOn(Function<S,U> mapper)
{
return new IsSortedByMatcher<>(mapper, false);
}
@Factory
public static <S, U extends Comparable<U>> IsSortedByMatcher<S,U> isSortedReverselyOn(Function<S,U> mapper)
{
return new IsSortedByMatcher<>(mapper, true);
}
}