Clean Guava way to handle possibly-null collection

前端 未结 2 446
挽巷
挽巷 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()));
    

提交回复
热议问题