迭代两个具有不同大小的同一时间列表

时间:2013-01-25 12:02:05

标签: java

我有两个清单X,Y。

哪些是字符串列表。

这两个列表有可能有不同的大小。

如果两个列表的大小都相同,那么我可以像

那样进行程序化
   for (int i =0;  i<anyList.size(); i++){
     system.out.printLn(X(i) +" "+Y(i));
  }

example result  :

stringX1 stringY1 
stringX2 stringY2

我如何处理具有不同大小的循环

示例结果应该如下所示

示例结果:

    stringX1 stringY1 
    stringX2 stringY2
    stringX3
    stringX4

6 个答案:

答案 0 :(得分:8)

Iterator<String> x_it = x.iterator();
Iterator<String> y_it = y.iterator();
while(x_it.hasNext() && y_it.hasNext()){
   System.out.println(x.next() + " " + y.next())
}
while(x_it.hasNext()){
   System.out.println(x.next());
}

while(y_it.hasNext()){
   System.out.println(y.next());
}

答案 1 :(得分:1)

for (int i =0;  i<max(X.size(),Y.size()); i++){
  if(i<X.size() && i<Y.size()) {
    print(X.get(i) + " " + Y.get(i));
  } else if(i<Y.size()) {
    print(Y.get(i));
  } else {
    print(X.get(i));
  }
}

编写max(int,int)和print(String)方法不应该很难。

答案 2 :(得分:1)

if(arr1.size()>=arr2.size())
    max  = arr1.size();
else
    max = arr2.size();

for(int i=0;i<max;i++)
{
    if(arr1.size() >= i+1)
        System.out.println(arr1.get(i));
    if(arr2.size() >= i+1)
    System.out.println(arr2.get(i));
}

答案 3 :(得分:0)

public static void main(String[] args) {
    List<String> l1 = new ArrayList<String>();
    l1.add("Pif");
    l1.add("Paf");
    l1.add("Pouf");
    List<String> l2 = new ArrayList<String>();
    l2.add("Argh!");
    l2.add("Aie!");

    Iterator<String> it1 = l1.iterator();
    Iterator<String> it2 = l2.iterator();

    String s1, s2;
    while (it1.hasNext() || it2.hasNext()) {
        if (it1.hasNext()) {
            s1 = it1.next();
            System.out.print(s1 + " - ");
        }
        if (it2.hasNext()) {
            s2 = it2.next();
            System.out.print(s2);
        }
        System.out.println();
    }


}

哪个收益率:

Pif - Argh!
Paf - Aie!
Pouf - 

答案 4 :(得分:0)

List<String> shorter = Arrays.asList("red", "blue");
List<String> longer = Arrays.asList("one", "two", "three", "four");

int size = Math.max(shorter.size(), longer.size());

StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {

  if (shorter.size() > i) {
    sb.append(shorter.get(i)).append('\t');
  } else {
    sb.append("\t\t");
  }

  if (longer.size() > i) {
    sb.append(longer.get(i));
  }

  sb.append('\n');
}

System.out.println(sb.toString());

输出

red   one
blue  two
      three
      four

答案 5 :(得分:0)

 int size = x.size() > y.size ? x.size() : y.size();
 for (int i =0;  i< size ; i++)
 {
     System.out.printLn( ( x.size() > i + 1 ? X(i) : "") +" "+( y.size() > i + 1 ? Y(i) : "") );
  }