Reputation: 122008
I have two list X,Y.
Which are lists of Strings .
there is a possibility to have the two lists different sizes .
If both lists are of same size of 2 then i can procedd like
for (int i =0; i<anyList.size(); i++){
system.out.printLn(X(i) +" "+Y(i));
}
example result :
stringX1 stringY1
stringX2 stringY2
how can i handle the loop which have different sizes
example result should be look like this
example result :
stringX1 stringY1
stringX2 stringY2
stringX3
stringX4
Upvotes: 0
Views: 5581
Reputation: 1565
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));
}
Upvotes: 1
Reputation: 64632
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());
output
red one
blue two
three
four
Upvotes: 0
Reputation: 10876
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) : "") );
}
Upvotes: 0
Reputation: 1447
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));
}
}
Programming a max(int, int) and print(String) method shouldn't be to hard.
Upvotes: 1
Reputation: 699
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();
}
}
Which yields:
Pif - Argh!
Paf - Aie!
Pouf -
Upvotes: 0
Reputation: 16355
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());
}
Upvotes: 9