1

I have a java list of URLs. I wish to call a function for each URL in the list. And this function adds URL to the list. Is it possible to loop over all the URLs including newly added URLs in the list?

for(String links: urls) {
    ar = getNews(links);
}

inside getNews() there is:

urls.add(json.optString("next"));

I did this successfully using recursion. By calling:

getNews(json.optString("next"));

inside getNews()

2
  • 1
    recursion works. Or, you can use the indexed loop (for i = 0; ...), since it allows concurrent modification, and checks for the exit condition at every iteration Commented Mar 8, 2016 at 7:59
  • can you also post getNews function code here i just want to know what is the use of getNews function here Commented Mar 8, 2016 at 8:01

2 Answers 2

2

You can use regular for loop and change the condition each iteration

int size = 1;
for (int i = 0 ; i < size ; ++i) {
    ar = getNews(urls.get(i));
    size = urls.size();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Iti mght be clearer if you updated URLs inside the loop.
@AndyTurner true, but I based it on the OP code, maybe there is more functionality in getNews()
getNews() method is meant to fetch JSON object from a link and adds a string of tag "title" to an array and returns it.. also fetches pagination and adds it to url list. so URL can't be updated from inside loop directly.. that's why i am looping the function over the list
2

Use a Queue instead of a list:

Queue<String> q = new LinkedList<>();
q.add(initial urls);
while (!q.isEmpty()) {
  String url = q.pop();
  q.addAll(readNews(url));
}

I am assuming that this code lives outside the readNews method, i.e. there is no recursion here.

Also, since I assume this is some sort of crawler, you might want to keep track of URLs you visited previously, to avoid visiting them again:

Queue<String> q = new LinkedList<>();
Set<String> visited = new LinkedHashSet<>();
q.add(initial urls);
while (!q.isEmpty()) {
  String url = q.pop();
  if (visited.add(url)) {
    q.addAll(readNews(url));
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.