Logo

Programming-Idioms

  • C++
  • Java
import java.util.HashSet;
import java.util.ArrayList;
x = new ArrayList<T>(new HashSet<T>(x));

This creates a new ArrayList object.
Original ordering is not preserved.
import java.util.ArrayList;
import java.util.LinkedHashSet;
x = new ArrayList<>(new LinkedHashSet<>(x));
import java.util.HashSet;
import java.util.Iterator;
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);
  }
}

Preserves the order of the items.
Upon first occurrence, store item in seen; all future occurrences of the item are removed from the list via the iterator listIt, removing the last-returned item.
Requires extra memory for the hash-set.

Note that the runtime cost is O(n^2).
import java.util.HashSet;
import java.util.List;
import java.util.Set;
Set<T> uniques = new HashSet<>(x);
x.clear();
x.addAll(uniques);

This uses the same List instance, emptied and then refilled.
Original ordering is not preserved.
import java.util.Iterator;
import java.util.List;
Iterator<T> g;
T t;
int i, n;
for (i = 0, n = x.size(); i < n; ++i) {
    t = x.get(i);
    g = x.listIterator(i + 1);
    while (g.hasNext())
        if (g.next().equals(t)) {
            g.remove();
            --n;
        }
}
#include <string>
#include <unordered_set>
#include <vector>
std::vector<std::string> x = {"one", "two", "two", "one", "three"};
std::unordered_set<std::string> t;
for (auto e : x)
    t.insert(e);

Original order is lost.
t contains the new list of unique objects.
#include <algorithm>
#include <vector>
std::sort(x.begin(), x.end());
auto last = std::unique(x.begin(), x.end());
x.erase(last, x.end());

List x must be a STL container like a std::vector.
(distinct x)

New implementation...
< >
programming-idioms.org