You simply need a generic method to do that.
The idea is to take a custom Comparator
that lets you compare the type, or your types should be comparable (should implement Comparable
).
The following code shows this:
public <T extends Comparable<T>> boolean checkPattern(List<T> list) {
return checkPattern(list, T::compareTo);
}
public <T> boolean checkPattern(List<T> list, Comparator<T> comparator) {
// assuming null/empty/list with 1 element satisfy the pattern
if (list == null || list.size() == 0 || list.size() == 1)
return true;
if (comparator.compare(list.get(0), list.get(1)) >= 0)
return false;
for (int i = 1; i < list.size() - 1; i++) {
T current = list.get(i);
T next = list.get(i + 1);
if (comparator.compare(current, next) <= 0) {
System.out.println(current + " " + next);
return false;
}
}
return true;
}
You can call it like:
System.out.println(new Test().checkPattern(Arrays.asList(3.2675781, 3.2800293, 3.232666, 3.1662598, 3.0898438, 3.0302734, 3.0253906, 2.9074707, 2.9343262, 2.9179688)));
And the output for this will be:
false
because 2.9074707 < 2.9343262
.
Talking about the efficiency, the asymptotic complexity of the above solution is O(n)
where n
is the number of elements in the input list. We can't do better than this as we need to visit every element of the list (except the last one) to check if satisfy the condition or not.