【问题标题】:Sorting ArrayList of Objects by objects property and organize them按对象属性对对象的 ArrayList 进行排序并组织它们
【发布时间】:2014-07-02 14:43:21
【问题描述】:

我正在编写一个 Java 应用程序,它应该读取每行记录的输入文件,并且字段用逗号分隔。应用程序的输出应在标准输出上,格式如下:

Age1
  Sex1
    name1
    name2
  Sex2
    name3
    name4
e.g
33
  Female
    Jayanta
    Kanupriya
44
  Female
    Lajjo
    Rajjo
  Male
    Raghav
    Sitaram

等等……

我创建了一个 Person 类来保存数据,并实现了 Comparable 接口,其中 compareTo 接口对年龄进行初级排序,对性别进行次级排序。我可以稍后在名称上添加三级排序。

public class Person implements Comparable<Person>{

    private String name;
    private int age;
    private String sex;

    /**
     * @param age, sex and name
     */
    public Person(String name, int age, String sex) {
        this.setName(name);
        this.setAge(age);
        this.setSex(sex);

    }

  //getters and setters

    @Override
    public int compareTo(Person person) {
        return this.age < person.getAge()?-1:this.age > person.getAge()?1:sortOnGender(person);
    }

     public int sortOnGender(Person person) {
        if (this.sex.compareToIgnoreCase(person.getSex()) < 0) {
            return -1;
        }
        else if (this.sex.compareToIgnoreCase(person.getSex()) > 0) {
            return 1;
        }
        else {
            return 0;
        }
    }

     @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.valueOf(this.age)).append('-').append(this.sex).append('-').append(this.name);
        return sb.toString();
    }
}

接下来在主方法的 App 类中,我创建了一个 ArrayList 的 Persons 并填充数据并使用 Collections.sort() 进行排序。我打印了 ArrayList 和它的排序顺序。但是问题是如何获取所需格式的数据。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

public class App {

    //An array of persons
    private static List<Person> persons = new ArrayList<Person>();

    public static void main(String[] args) {

        File inputfile = new File(args[0]);

        if(inputfile.exists()) {
            String line;
            BufferedReader br;
            StringTokenizer st = null;
            try {
                br = new BufferedReader(new FileReader(inputfile));
                // Read comma seperated file line by line
                while((line = br.readLine()) != null) {

                    //Break the line using "," as field seperator
                    st = new StringTokenizer(line, ",");

                    // Number of columns in the line
                    int numcols = st.countTokens();

                    if(numcols > 0) {
                        String[] cols = new String[st.countTokens()];

                        // Till the time columns are there in the line
                        while(st.hasMoreTokens()) {
                            for(int i=0; i < numcols; i++) {
                                cols[i] = st.nextToken();
                            }
                        }

                        // If there are elements in the cols array
                        if(cols.length !=0) {
                            // Create a list of persons
                            persons.add(new Person(cols[0].trim(), Integer.parseInt(cols[1].toString().trim()), cols[2].trim()));
                        }
                    }
                    else {
                        // Print error and continue to next record (Takes care of blank lines)
                        System.err.println("Error: No columns found in line");
                    }
                }
                // Sort the Collection
                Collections.sort(persons);
                br.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }

        }
        else {
            System.out.println("Specify the location of the input file");
        }

        System.out.println(persons);

    }
}

【问题讨论】:

  • “所需格式”究竟是什么?又是什么格式?
  • 欢迎来到 SO。你尝试过什么来解决这个问题?
  • 看起来好像您想按操作执行 n 维分组,在您的示例中,n = 2。Guava 可以帮助您执行此操作,或者您可以自己执行此操作
  • @Daniel - 感谢您的欢迎。我试图通过逻辑思考,但无法弄清楚如何进行。
  • @Lutz - 所需格式在顶部给出。

标签: java sorting arraylist


【解决方案1】:

我不确定我是否关注你,但你只需要编写一个可以按你想要的方式显示的方法!

如果您想在控制台中打印,可以尝试以下操作:

Public printListPersons(persons[] p){
   for(Person p : persons){
       System.out.println(p[i].getAge);
       System.out.println("\n");
       System.out.println("\t" + p[i].getSex);
       ....
   }
}

【讨论】:

    【解决方案2】:

    一旦你有一个排序列表,你应该能够做这样的事情

    int currentAge = -1;
    String currentSex = null;
    
    for (Person person : persons) {
        if (person.getAge() != currentAge) {
            currentAge = person.getAge();
            currentSex = null;
            System.out.println(person.getAge());
        }
        if (!person.getSex().equals(currentSex)) {
            currentSex = person.getSex();
            System.out.println("\t" + person.getSex());
        }
    
        System.out.println("\t\t" + person.getName());
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-21
      • 2011-09-06
      • 2011-02-16
      相关资源
      最近更新 更多