Clean Guava way to handle possibly-null collection

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

提交回复
热议问题