Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"For each" loop for two object

Tags:

java

for-loop

ArrayList<String> date=new ArrayList<String>();
ArrayList<String> time=new ArrayList<String>();
//addition of elements in the list
...
...
for(String x :date,String y: time)
{
    System.out.println(x+" "+y);
}

Is two objects can be iterate by single "for each" loop? i tried above code,i got compilation error. Is any syntax mistake is there?

like image 604
anavaras lamurep Avatar asked Sep 19 '26 17:09

anavaras lamurep


2 Answers

Nope, this isn't going to work. There is no way to do this with a for-each loop; you will have to do a normal for loop with either explicit indices or with iterators.

like image 182
Louis Wasserman Avatar answered Sep 22 '26 07:09

Louis Wasserman


There is no built-in functionality, but there are third-party libraries and freely available code for Java-8 that let you do this:

Stream<String> a = Stream.of(date);
Stream<String> b = Stream.of(time);

List<String> zip = StreamUtils.zip(a, b,
                                  (a, b) -> a + " " + b)
                             .collect(Collectors.toList());

If you are not using Java 8 or are not comfortable using streams, using a for loop with an index or iterating two iterators is the next closest thing:

Iterator<String> a = date.iterator();
Iterator<String> b = time.iterator();
while (a.hasNext() && b.hasNext()) {
    System.out.println(a.next() + " " + b.next());
}

Demo.

like image 24
Sergey Kalinichenko Avatar answered Sep 22 '26 08:09

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!