我有2套:
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];
我正在寻找一种方法将set2
的值附加到set1
并将其存储在set3
设置3输出
set3 = [AB, CD, EF]
答案 0 :(得分:14)
您需要使用Iterator
来保持TreeSet
的顺序。您可以致电TreeSet.iterator()
:
以升序返回此集合中元素的迭代器。
假设两个集合的长度相同,您可以:
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]"
}
如果该集具有不同的大小且是错误,您可以在while
循环之前添加以下检查:
if (set1.size() != set2.size()) {
throw new IllegalArgumentException("Can't merge sets of different size");
}
作为参考,您可以使用来自this answer的zip
实用程序使用Java 8进行此操作:
Set<String> set3 = zip(set1.stream(), set2.stream(), String::concat)
.collect(Collectors.toCollection(TreeSet::new));
答案 1 :(得分:7)
这是使用 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);
<强>输出强>
[AB, CD, EF]
具有功能成语的Java 8变体(有点难看)
// 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);
<强>输出强>
[AB, CD, EF]
答案 2 :(得分:2)
另一种方法是使用将zip
添加到Java 8 streams
的库,例如https://github.com/poetix/protonpack或https://github.com/jOOQ/jOOL
答案 3 :(得分:0)
我非常不喜欢while (it1.hasNext())
,所以我的方式:
1)
Iterator<String> iterator2 = set2.iterator();
for(String s : set1) {
set3.add(s.concat(iterator2.next()));
}
System.out.println(set3);
2)或
List<String> list = new ArrayList<String>(set2);
int i = 0;
for(String s : set1) {
set3.add(s.concat(list.get(i)));
i++;
}
System.out.println(set3);
3)(1)带支票:
Iterator<String> iterator2 = set2.iterator();
for(String s : set1) {
set3.add(s.concat(iterator2.hasNext()? iterator2.next(): ""));
}
System.out.println(set3);
4)(2)带支票:
List<String> list = new ArrayList<String>(set2);
int i = 0;
for(String s : set1) {
set3.add(s.concat(list.size() > i? list.get(i): ""));
i++;
}
System.out.println(set3);