0

我有两个列表 X,Y。

哪些是 Strings 列表。

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

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

   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
4

6 回答 6

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());
}
于 2013-01-25T12:08:07.450 回答
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) 方法应该不难。

于 2013-01-25T12:11:02.620 回答
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));
}
于 2013-01-25T12:26:06.117 回答
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 - 
于 2013-01-25T12:10:44.747 回答
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
于 2013-01-25T12:12:11.467 回答
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) : "") );
  }
于 2013-01-25T12:12:59.897 回答