简体   繁体   中英

Jsoup: sort Elements

I need to sort a Jsoup Elements container by its ownText(). What is a recommended way to accomplish that?

Does convertinng it to an ArrayList first for use with a custom comparator make sense?

BTW, I tried sorting it directly, as in Collections.sort(anElementsList) but the compiler complains:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for
the arguments (Elements). The inferred type Element is not a valid substitute for the 
bounded parameter <T extends Comparable<? super T>>

The Jsoup Elements already implements Collection , it's essentially a List<Element> , so you don't need to convert it at all. You just have to write a custom Comparator<Element> for Element because it doesn't implement Comparable<Element> (that's why you're seeing this compile error).

Kickoff example:

String html ="<p>one</p><p>two</p><p>three</p><p>four</p><p>five</p>";
Document document = Jsoup.parse(html);
Elements paragraphs = document.select("p");

Collections.sort(paragraphs, new Comparator<Element>() {
    @Override
    public int compare(Element e1, Element e2) {
        return e1.ownText().compareTo(e2.ownText());
    }
});

System.out.println(paragraphs);

Result:

<p>five</p>
<p>four</p>
<p>one</p>
<p>three</p>
<p>two</p>

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM