Jsoup:排序元素

ef2*_*011 3 java collections jsoup

我需要按其 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>>
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 5

JsoupElements已经实现了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);
Run Code Online (Sandbox Code Playgroud)

结果:

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);
Run Code Online (Sandbox Code Playgroud)

也可以看看: