What is an efficient and elegant way to add a single element to an immutable set?

后端 未结 7 763
谎友^
谎友^ 2020-12-29 21:40

I have an immutable set (cast as a Set) that potentially contains many elements. I need a Collection that contains the elements from that set plu

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 22:12

    You might consider Sets.union(). Construction would be faster, but use slower.

    public static  Set setWith(Set old, T item) {
      return Sets.union(old, Collections.singleton(item);
    }
    

    (com.google.common.collect.Sets & java.util.Collections)

提交回复
热议问题