Skip to content

Commit 8b9d961

Browse files
committed
go back to iterators
1 parent 7d1b5ee commit 8b9d961

File tree

2 files changed

+11
-8
lines changed

2 files changed

+11
-8
lines changed

server/src/main/java/org/elasticsearch/common/util/CollectionUtils.java

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,22 +50,24 @@ public static <T> void uniquify(List<T> list, Comparator<T> cmp) {
5050
return;
5151
}
5252

53-
int resultIndex = 0;
54-
int currentIndex = 1;
55-
T lastValue = list.get(resultIndex); // get first element to compare with
53+
ListIterator<T> resultItr = list.listIterator();
54+
ListIterator<T> currentItr = list.listIterator(1); // start at second element to compare
55+
T lastValue = resultItr.next(); // result always includes first element, so advance it and grab first
5656
do {
57-
T currentValue = list.get(currentIndex);
57+
T currentValue = currentItr.next(); // each iter we check if the next element is different from the last we put in the result
5858
if (cmp.compare(lastValue, currentValue) != 0) {
5959
lastValue = currentValue;
60-
if (++resultIndex != currentIndex) {
61-
list.set(resultIndex, currentValue);
60+
resultItr.next(); // advance result so the current position is where we want to set
61+
if (resultItr.previousIndex() != currentItr.previousIndex()) {
62+
// optimization: only need to set if different
63+
resultItr.set(currentValue);
6264
}
6365
}
64-
} while (++currentIndex < list.size());
66+
} while (currentItr.hasNext());
6567

6668
// Lop off the rest of the list. Note with LinkedList this requires advancing back to this index,
6769
// but Java provides no way to efficiently remove from the end of a non random-access list.
68-
list.subList(resultIndex + 1, list.size()).clear();
70+
list.subList(resultItr.nextIndex(), list.size()).clear();
6971
}
7072

7173
/**

server/src/test/java/org/elasticsearch/common/util/CollectionUtilsTests.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ public void testUniquify() {
7575
assertUniquify(List.<Integer>of(), Comparator.naturalOrder(), 0);
7676
assertUniquify(List.of(1), Comparator.naturalOrder(), 1);
7777
assertUniquify(List.of(1, 2, 3), Comparator.naturalOrder(), 3);
78+
assertUniquify(List.of(1, 1, 3), Comparator.naturalOrder(), 2);
7879
assertUniquify(List.of(1, 1, 1), Comparator.naturalOrder(), 1);
7980
assertUniquify(List.of(1, 2, 2, 3), Comparator.naturalOrder(), 3);
8081
assertUniquify(List.of(1, 2, 2, 2), Comparator.naturalOrder(), 2);

0 commit comments

Comments
 (0)