Daniele
Daniele

Reputation: 329

How to return the index Element in an Elements list using jsoup?

I have two lists I need to both iterate at the same time, getting the same n-th element from them. This how I solved:

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
[...]
int idx = 0;

for(Element A : ListA) {    
    String B = ListB.eq(idx).text();
    System.out.println(A.text()+ " " + B);
    ++idx;
}

In order to return the following output:

A1 B1

A2 B2

...

An Bn

It'd be cleaner if I could extract from ListA the current n-th element index. But how? I did not find any suitable method.

Any clue? Thanks in advance.

Upvotes: 1

Views: 3280

Answers (2)

TDG
TDG

Reputation: 6161

Look at the Elements class' hierarchy - Elements. It extends ArrayList and if you scroll down you'll see that it inherits get, so the following code snippet is possible:

Elements elements = doc.select("some css selector");
Element e = elements.get(index);
System.out.println(e.get(anotherIndex).html());

So you can use an index to get an specific Element from Elements list.

Upvotes: 2

senerh
senerh

Reputation: 1365

I don't know if it works, but you can try ListA.indexOf(A) to get the current index.

Upvotes: 1

Related Questions