Remove duplicates from List using Guava

后端 未结 6 1058
清歌不尽
清歌不尽 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:23

    I love Louis' answer for the simplicity of it (and because it's the only answer that doesn't require 2 full iterations), but unfortunately in the real world, you often encounter situations where null does occur. Here's a slightly longer null-safe version:

    ImmutableSet.copyOf(
        Iterables.filter(
            list, Predicates.not(Predicates.isNull()))).asList();
    

    Or, with static imports:

    copyOf(filter(list, not(isNull()))).asList();
    

    Of course you need to be aware of the fact that all null Values will be lost from the List.

提交回复
热议问题