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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With