问题描述
我需要按其ownText()对Jsoup Elements容器进行排序.建议采用什么方法来实现这一目标?
I need to sort a Jsoup Elements container by its ownText(). What is a recommended way to accomplish that?
首先将其转换为ArrayList以便与自定义比较器一起使用有意义吗?
Does convertinng it to an ArrayList first for use with a custom comparator make sense?
顺便说一句,我尝试像在Collections.sort(anElementsList)
中那样直接对其进行排序,但是编译器抱怨:
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>>
推荐答案
Jsoup Elements
已实现 ,它实际上是 List<Element>
,因此您根本不需要对其进行转换.您只需要编写自定义 Comparator<Element>
表示 Element
,因为它没有实现 Comparable<Element>
(这就是为什么您看到此编译错误).
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).
开球示例:
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>
另请参见:
- 根据姓名排序联系人的数组列表?
- Sorting an ArrayList of Contacts based on name?
See also:
这篇关于Jsoup:对元素进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!