Remove duplicates from List using Guava

后端 未结 6 1062
清歌不尽
清歌不尽 2020-12-08 06:45

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

Currently I am following this:

private List removeDuplic         


        
6条回答
  •  春和景丽
    2020-12-08 07:31

    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.

提交回复
热议问题