Let's say I want to calculate the union of 2 sets, set1
and set2
, and assign the result to set3
. I do not want to change the values of set1
and set2
.
I know I can do it like this:
Set<String> set1 = new HashSet<String>(); set1.add("a");
Set<String> set2 = new HashSet<String>(); set2.add("b");
Set<String> set3 = new HashSet<String>(set1); // copy constructor
set3.addAll(set2);
But I was wondering if there is a more direct syntax like:
Set<String> set3 = (new HashSet<String>(set1)).addAll(set2);
or
Set<String> set3 = new HashSet<String>();
set3.addAll(set1).addAll(set2);
The ways I've tried don't work because addAll()
returns a boolean, not the result Set object.