Jsoup:排序元素组

时间:2015-07-08 08:17:41

标签: java jsoup

我使用Jsoup显示50个项目的列表,每个项目包含一组4个元素:标题,价格,位置和日期。

try {   
    Document doc = Jsoup.connect(URL).userAgent("Chrome").timeout(5000).get();

    Elements titles = doc.select("myCssQuery");
    Elements prices = doc.select("myCssQuery");
    Elements locations = doc.select("myCssQuery");
    Elements dates = doc.select("myCssQuery");
    //Elements itemUrls = doc.select("myCssQuery");

    for(int i = 0; i < titles.size()-1; i++) {
       System.out.println(titles.get(i).text());
       System.out.println(prices.get(i).text());
       System.out.println(locations.get(i).text());
       System.out.println(dates.get(i).text());
       System.out.println();
       //System.out.println(itemUrls.get(i).attr("abs:href"));
   }

} catch (IOException e) {
    e.printStackTrace();
}

现在我必须按价格对列表进行排序(当前是字符串,但可以转换为int)。但我知道完成这项任务的唯一方法是使用数据库,在这种情况下我不愿意这样做。有没有办法在不使用数据库的情况下实现这一目标?

1 个答案:

答案 0 :(得分:1)

只需使用Collections.sort(),我有一个简短的工具,这是按价格升序排序,您可以更改compareTo()以换取另一种排序方式:

public static void main(String[] args) throws IOException {
    Document doc = Jsoup.connect(URL).userAgent("Chrome").timeout(5000).get();

    Elements titles = doc.select("myCssQuery");
    Elements prices = doc.select("myCssQuery");
    Elements locations = doc.select("myCssQuery");
    Elements dates = doc.select("myCssQuery");

    List<Item> items = new ArrayList<>();
    Item item;
    for(int i = 0; i < titles.size()-1; i++) {
        item = new Item(titles.get(i).text(), Integer.parseInt(prices.get(i).text().replaceAll("\\D+","")), locations.get(i).text(), dates.get(i).text());    
        items.add(item);
    }

    Collections.sort(items, new Comparator<Item>() {
        @Override
        public int compare(Item item1, Item item2) {
            return item1.compareTo(item2);
        }
    });

}

public static class Item implements Comparable {
    private String title;
    private int price;
    private String location;
    private String date;

       public Item(String title, int price, String location, String date) {
        this.title = title;
        this.price = price;
        this.location = location;
        this.date = date;
       }

    @Override
    public int compareTo(Object o) {
        Item item = (Item) o;
        if (this.price == item.price) {
            return 0;
        } else if (this.price > item.price) {
            return 1;
        } else {
            return -1;
        }
    }
}

或者你可以实现sort into compare()不需要在类Item中实现Comparable,如下所示:

Collections.sort(items, new Comparator<Item>() {
    @Override
    public int compare(Item item1, Item item2) {
        if (item1.getPrice() == item2.getPrice()) {
            return 0;
        } else if (item1.getPrice() > item2.getPrice()) {
            return 1;
        } else {
            return -1;
        }
    }
});