Java - Executing two corrosponding for loops at same time

I have two for loops written in java below. The first one grabs all the titles of news articles on a website, and the second one grabs all the links of the same new articles on the same website.

How do I make it so that when the first loop executes once, the second loop executes once, and then the first loop executes a second time, and the second one executes a second time, etc. I would really appreciate your help, thanks.

for( org.jsoup.nodes.Element element : elements1 ){

   sendMessageRequest.setText(element.text());


   sendMessage(sendMessageRequest);
   System.out.print("sent message");
}

for( org.jsoup.nodes.Element element : elements2 ) {

   sendMessageRequest.setText(element.text());


   sendMessage(sendMessageRequest);
   System.out.print("sent message");
}

Upvotes: 2

Views: 350

Answers (2)

Andreas
Andreas

Reputation: 159114

I'm going to assume that elements1 and elements2 are some kind of Iterable<Element>, e.g. List<Element>.

First, remember that for (Element element : elements1) is just syntactic sugar for:

Iterator<Element> iter = elements1.iterator();
while (iter.hasNext()) {
    Element element = iter.next();
    // code here
}

Except that you don't have access to the Iterator.

So, if you want to iterate two different Iterable objects, do so the old-fashioned way:

Iterator<Element> iter1 = elements1.iterator();
Iterator<Element> iter2 = elements2.iterator();
while (iter1.hasNext() && iter2.hasNext()) {
    Element element1 = iter1.next();
    Element element2 = iter2.next();
    // code here
}

If the two Iterable objects are not the same length, the loop will only iterate until the shorter one has been exhausted. Extra elements in the other one will simply be ignored.

Upvotes: 4

Matthew Diana
Matthew Diana

Reputation: 1106

If elements1 and elements2 are guaranteed to have the same length, just iterate through them into one loop:

for (int i = 0; i < elements1.length; i++) {
    processMessageRequest(elements1[i]);
    processMessageRequest(elements2[i]);
}

Using a new method processMessageRequest to make your code more DRY:

private void processMessageRequest(Element e) {
    sendMessageRequest.setText(e.text());
    sendMessage(sendMessageRequest);
    System.out.println("sent message");
}

I'm not sure what the scope of sendMessageRequest is... but with some tweaking this way could work.

Upvotes: 0

Related Questions