[英]Jsoup: sort Elements
我需要按其ownText()对Jsoup Elements容器进行排序。 建议采用什么方法来实现这一目标?
首先将其转换为ArrayList以便与自定义比较器一起使用是否有意义?
顺便说一句,我试图直接对其进行排序,如Collections.sort(anElementsList)
但是编译器抱怨:
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>>
Jsoup Elements
已经实现了Collection
,它实际上是一个List<Element>
,因此您根本不需要对其进行转换。 你只需要编写一个自定义Comparator<Element>
的Element
,因为它没有实现Comparable<Element>
(这就是为什么你看到此编译错误)。
开球示例:
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);
结果:
<p>five</p>
<p>four</p>
<p>one</p>
<p>three</p>
<p>two</p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.