Logo

Programming-Idioms

History of Idiom 119 > diff from v30 to v31

Edit summary for version 31 by canonical.chris:
New Java implementation by user [canonical.chris]

Version 30

2018-03-09, 13:34:19

Version 31

2018-04-07, 10:20:55

Idiom #119 Deduplicate list

Remove duplicates from list x.
Explain if original order is preserved.

Illustration

Idiom #119 Deduplicate list

Remove duplicates from list x.
Explain if original order is preserved.

Illustration
Extra Keywords
deduplicate dupe dupes redundant redundancy
Extra Keywords
deduplicate dupe dupes redundant redundancy
Imports
import java.util.HashSet;
Code
final HashSet<T> seen = new HashSet<T>();
final Iterator<T> listIt = x.iterator();
while (listIt.hasNext()) {
  final T curr = listIt.next();
  if (seen.contains(curr)) {
    listIt.remove();
  } else {
    seen.add(curr);
  }
}
Comments bubble
Preserves the order of the items.
Upon first occurrence, store item in seen; all future occurrences of the item remove it from the list via the iterator, which removes the last-returned item.
Doc URL
https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html