Reputation: 3251
I have two sets:
val Set<Integer> setA = #{1, 2, 3}
val Set<Integer> setB = #{3, 4, 5} + setA
I would expect setB
to contain 1, 2, 3, 4, 5.
However, the +
operator returns an instance of Iterable
, instead of a Set
.
Are there any xtend shortcuts that would allow me to do what I want?
Upvotes: 2
Views: 329
Reputation: 29969
Without redefining operators, you have to convert the Iterable
to a Set
manually.
val Set<Integer> setA = #{1, 2, 3}
val Set<Integer> setB = (#{3, 4, 5} + setA).toSet
If you have a mutable set, there is one other way: The +=
operator, which is a shortcut for addAll
on any collection.
val Set<Integer> setA = #{1, 2, 3}
val Set<Integer> setB = newHashSet(3, 4, 5)
setB += setA
Neither solution look particularly nice and you probably want to avoid mutability.
As suggested in the other answer, Guava's Sets.union
method might come in handy, though I would rather import it as static extension than redefining operators. Then you can use:
val Set<Integer> setA = #{1, 2, 3}
val Set<Integer> setB = #{3, 4, 5}.union(setA)
Be careful though, union
returns a view of both sets, which can change if the underlying sets are mutable.
Upvotes: 0
Reputation: 6729
I'm afraid there is no backed in support for a union. You may want to add an operator_plus
for two sets and delegate to Guavas Sets.union
.
def <T> Set<? extends T> operator_plus(Set<? extends T> left, Set<? extends T> right) {
return Sets.union(left, right)
}
Upvotes: 2