根据列对行进行排序 [英] Sorting lines based on column

查看:260
本文介绍了根据列对行进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以根据列进行排序吗?

Is there any way where we can sort based on columns?

我有类似的行,

1000 Australia     Kangaroo            Canberra
1002 India         Tiger               Delhi
1092 Germany       Eagle               Berlin

上述行必须排序基于第二列,即澳大利亚,德国,印度。

The above lines has to be sorted based on the second column, that is Australia, Germany, India.

所以,结果应该是,

1000 Australia     Kangaroo            Canberra
1092 Germany       Eagle               Berlin   
1002 India         Tiger               Delhi

数据来自文本文件

推荐答案

我建议使用 TreeSet 并阅读你的文本文件将您的数据保存在实现 Comparable 的类中。这样,当您添加到 TreeSet 时,数据将按排序顺序添加。

I would suggest using a TreeSet and reading your text file and keeping your data in a class that implements Comparable. That way, when you're adding to the TreeSet the data would get added in a sorted order.

这个例子可能会有所帮助:

This example might help:

class Data implements Comparable<Data>{

    private int digits;
    private String country;
    private String animal;
    private String capital;

    public Data(int digits, String country, String animal, String capital){
        this.digits = digits;
        this.country = country;
        this.animal = animal;
        this.capital = capital;
    }

    public int getDigits() {
        return digits;
    }

    public void setDigits(int digits) {
        this.digits = digits;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getAnimal() {
        return animal;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public String getCapital() {
        return capital;
    }

    public void setCapital(String capital) {
        this.capital = capital;
    }

    @Override
    public int compareTo(Data data) {
        return getCountry().compareTo(data.getCountry());
    }
}


class TestCountry{
    public static void main(String[] args) {
        TreeSet<Data> set = new TreeSet<Data>();
        /** 
         * Assuming that you can read the CSV file and build up the Data objects.
         * You would then put them in the set where they will be added in a sorted
         * fashion 
         */
        set.add(new Data(1000, "Australia", "Kangaroo", "Canberra"));
        set.add(new Data(1002, "India", "Tiger", "Delhi"));
        set.add(new Data(1092, "Germany", "Eagle", "Berlin"));

        for(Data data: set){
            System.out.println(data.getDigits()+"\t"+data.getCountry()+"\t"+data.getAnimal()+"\t"+data.getCapital());
        }
    }
}

这篇关于根据列对行进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆