You need to use an Iterator
to keep the order of the TreeSet
. You can get it by calling TreeSet.iterator()
:
Returns an iterator over the elements in this set in ascending order.
Assuming that both sets have the same length, you could have:
public static void main(String[] args) {
Set<String> set1 = new TreeSet<String>(Arrays.asList("A", "C", "E"));
Set<String> set2 = new TreeSet<String>(Arrays.asList("B", "D", "F"));
Set<String> set3 = new TreeSet<String>();
Iterator<String> it1 = set1.iterator();
Iterator<String> it2 = set2.iterator();
while (it1.hasNext() && it2.hasNext()) {
set3.add(it1.next() + it2.next());
}
System.out.println(set3); // prints "[AB, CD, EF]"
}
If the set have different size and that is an error, you could add the following check before the while
loop:
if (set1.size() != set2.size()) {
throw new IllegalArgumentException("Can't merge sets of different size");
}
For reference, you could make this using Java 8, using the zip
utility from this answer:
Set<String> set3 = zip(set1.stream(), set2.stream(), String::concat)
.collect(Collectors.toCollection(TreeSet::new));