Max Max - 1 year ago 74
Java Question

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

I have an immutable set (cast as a

) that potentially contains many elements. I need a Collection that contains the elements from that set plus one additional element. I have kludgy code in place to copy the set, then append the element, but I'm looking for The Right Way that keeps things as efficient as possible.

I have Guava available, though I do not require its use.

Answer Source

Not sure about performance, but you can use Guava's ImmutableSet.Builder:


// ...
Set<Integer> newSet = new ImmutableSet.Builder<Integer>()

Of course you can also write yourself a helper method for that:

public static <T> Set<T> setWith(Set<T> old, T item) {
  return new ImmutableSet.Builder<T>().addAll(old).add(item).build();

// ...
Set<Integer> newSet = setWith(oldSet, 3);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download