Jsoup: sort Elements

为君一笑 提交于 2020-03-22 08:09:08

问题


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>>

回答1:


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:

  • Sorting an ArrayList of Contacts based on name?


来源:https://stackoverflow.com/questions/7908402/jsoup-sort-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!