How can we remove duplicates from List with the help of Guava api?
Currently I am following this:
private List removeDuplic
I really don't recommend using (Linked)HashMultiSet
to do task which is usually done with ArrayList
and (Linked)HashSet
like OP mentioned above - it's less readable for regular Java programmer and (probably) less efficient.
Instead, at least use static factory constructors like newArrayList and newLinkedHashSet to avoid all these
s:
private static List removeDuplicate(final List list) {
return Lists.newArrayList(Sets.newLinkedHashSet(list));
}
However, you can do it in more "Guava way" - by avoiding nulls and using immutable collections.
So if your collection cannot have null elements, I'd suggest using immutable set instead of mutable and less efficient one:
private static List removeDuplicate(final List list) {
return Lists.newArrayList(ImmutableSet.copyOf(list));
}
It's still copying objects twice, so consider being fully-immutable and changing method signature to return ImmutableList
:
private static ImmutableList removeDuplicate(final List list) {
return ImmutableSet.copyOf(list).asList();
}
This way there is only one copying involved, because ImmutableCollection.asList() returns a view.