Clean Guava way to handle possibly-null collection

前端 未结 2 428
挽巷
挽巷 2021-01-18 23:51

I have a method which takes an argument Collection foos, which could be NULL. I want to end up with a local copy of the input as an ImmutableS

相关标签:
2条回答
  • 2021-01-19 00:23

    I don't see why you couldn't use Objects.firstNonNull:

    this.foos = ImmutableSet.copyOf(Objects.firstNonNull(foos, ImmutableSet.of()));
    

    You can save some typing with static imports, if that's your thing:

    import static com.google.common.collect.ImmutableSet.copyOf;
    import static com.google.common.collect.ImmutableSet.of;
    // snip...
    this.foos = copyOf(Objects.firstNonNull(foos, of()));
    
    0 讨论(0)
  • 2021-01-19 00:26

    A Collection is a reference like any other, so you could do:

    ImmutableSet.copyOf(Optional.fromNullable(foos).or(ImmutableSet.of()));
    

    But that is becoming quite a handful to write. More simple:

    foos == null ? ImmutableSet.of() : ImmutableSet.copyOf(foos);
    
    0 讨论(0)
提交回复
热议问题