如果你只是使用变量来保存每个迭代器的当前值,这是相当简单的.此解决方案假定您的列表不包含null,但由于列表已排序,因此添加空值处理并不困难.
package com.example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class IteratorMerge {
/**
* @param args
*/
public static void main(String[] args) {
List list1 = Arrays.asList(new String[]{"A", "B", "C", "D"});
List list2 = Arrays.asList(new String[]{"B", "D", "F", "G"});
System.out.println(merge(list1, list2));
}
public static List merge(List L1,List L2) {
List L3 = new ArrayList();
Iterator it1 = L1.iterator();
Iterator it2 = L2.iterator();
String s1 = it1.hasNext() ? it1.next() : null;
String s2 = it2.hasNext() ? it2.next() : null;
while (s1 != null && s2 != null) {
if (s1.compareTo(s2) < 0) { // s1 comes before s2
L3.add(s1);
s1 = it1.hasNext() ? it1.next() : null;
}
else { // s1 and s2 are equal, or s2 comes before s1
L3.add(s2);
s2 = it2.hasNext() ? it2.next() : null;
}
}
// There is still at least one element from one of the lists which has not been added
if (s1 != null) {
L3.add(s1);
while (it1.hasNext()) {
L3.add(it1.next());
}
}
else if (s2 != null) {
L3.add(s2);
while (it2.hasNext()) {
L3.add(it2.next());
}
}
return L3;
}
}