Remove duplicates from List using Guava

Priyank Doshi picture Priyank Doshi · Sep 3, 2012 · Viewed 26.4k times · Source

How can we remove duplicates from List with the help of Guava api?

Currently I am following this:

private List<T> removeDuplicate(List<T> list){
return new ArrayList<T>(new LinkedHashSet<T>(list));
}

Answer

Louis Wasserman picture Louis Wasserman · Sep 3, 2012

Probably the most efficient way is ImmutableSet.copyOf(list).asList(), which eliminates duplicates and preserves iteration order.

(But your implementation with LinkedHashSet would be nearly as efficient, and wouldn't throw up on nulls, in the unlikely event you actually wanted nulls in your collection.)