0
Connection con = Jsoup.connect(https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8); //Just giving an example
Document htmlDoc = con.get();       
Elements linksOnPage = htmlDoc.select("a[href]");
for(Element link : linksOnPage){
//pushing the links on to a stack
}

What I need is that I want to push the links retrieved in such a way that the first link retrieved from linksOnPage becomes my stack top.

1) Can someone suggest me if there is any other way to traverse the link object backwards?

2) Any other way? like for example what if I copy all those links in their order of arrival to a LinkedList and then traverse the list backwards? I understand that this could be a little naive method.

TDG
  • 5,909
  • 3
  • 30
  • 51
user3868051
  • 1,147
  • 2
  • 22
  • 43

2 Answers2

1

Since Elements is a list, you can do it like this -

if (linksOnPage.size() > 0) {
    for (int i = linksOnPage.size() - 1; i >=0; i--) {
        Element e = linksOnPage.get(i);
        //push e
    }
} 
TDG
  • 5,909
  • 3
  • 30
  • 51
1

Elements is already a ArrayList you just need to loop it backward like below.

Document htmlDoc = con.get();       
Elements linksOnPage = htmlDoc.select("a[href]");
for(int i=linksOnPage.size()-1;i>=0;i++)
        {
            System.out.println(linksOnPage.get(i));
        }

From Javadoc of jsoup

public class Elements
extends java.util.ArrayList<Element>
A list of Elements, with methods that act on every element in the list.
To get an Elements object, use the Element.select(String) method.
Rishal
  • 1,480
  • 1
  • 11
  • 19