I have 2 sets:
Set<String> set1 = new TreeSet<String>();
Set<String> set2 = new TreeSet<String>();
Set<String> set3 = new TreeSet<String>();
set1 = [A, C, E];
set2 = [B, D, F];
I am looking for a way to append the value of set2
to set1
and store them in set3
Set 3 Output
set3 = [AB, CD, EF]
Another way to do this is to use a library that adds zip
to Java 8 streams
such as https://github.com/poetix/protonpack or https://github.com/jOOQ/jOOL
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));
Here's a way to do this the imperative way, with Java 7:
Set<String> set1 = new TreeSet<String>(Arrays.asList(new String[]{"A", "C", "E"}));
Set<String> set2 = new TreeSet<String>(Arrays.asList(new String[]{"B", "D", "F"}));
Set<String> set3 = new TreeSet<String>();
// Java 7: imperative
// edit: checking sizes beforehand
if (set1.size() != set2.size())
throw new IllegalStateException("Sets aren't the same size!");
Iterator<String> iterator1 = set1.iterator();
Iterator<String> iterator2 = set2.iterator();
while (iterator1.hasNext()) {
String s = iterator1.next();
// assuming iterator2.hasNext() as sizes were checked previously
s = s.concat(iterator2.next());
set3.add(s);
}
System.out.println(set3);
Output
[AB, CD, EF]
Java 8 variant with functional idiom (a little ugly)
// Java 8: functional (but ugly)
Iterator<String> iterator2new = set2.iterator();
// edited, ensuring a `TreeSet` is returned
set3 =
set1
.stream()
.map((s) -> s.concat(iterator2new.next()))
.collect(Collectors.toCollection(TreeSet::new));
System.out.println(set3);
Output
[AB, CD, EF]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With