如何按升序排列输出?

时间:2015-02-15 03:06:08

标签: java

所以我编写代码来从文件中读取并进行一些计算,并生成如下输出:

First Name = tony
Last Name = wroten
Geometric Mean = 663002.7727000846
----------------------------

First Name = nick
Last Name = young
Geometric Mean 128740.18176156192

但它只是一个输出,并没有存储在任何地方。有没有办法按照几何平均值按升序排列输出?

1 个答案:

答案 0 :(得分:1)

  • 为您的文件信息创建一个持有者。例如PersonVO,根据我的代码如下。
  • 您阅读文件和为此人设置值的逻辑可能会发生变化。我刚刚给出了一个例子。
  • 完成后,将每个人添加到列表中
  • 然后对列表进行排序
  • 由于排序是基于特定属性的,因此我们必须根据以下示例创建一个自定义比较器,即PersonComparator

    public static void main(String[] args) {
    
    
                PersonVO person1 = new PersonVO("firstname1", "lastname1", 2.1);
                PersonVO person2 = new PersonVO("firstname2", "lastname2", 1.1);
    
                List<PersonVO> personList = new ArrayList<PersonVO>();
                personList.add(person1);
                personList.add(person2);
    
                System.out.println("Before Sort");
                System.out.println(personList);
    
                Collections.sort(personList, new PersonComparator());
                System.out.println("After Sort");
                System.out.println(personList);
            }
    

这是VO的示例实现,它包含从文件读取到类的每个人的信息。

public class PersonVO {


    public PersonVO(String firstName, String lastName, double mean) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.mean = mean;
    }
    private String firstName;
    private String lastName;
    private double mean;


    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public double getMean() {
        return mean;
    }
    public void setMean(double mean) {
        this.mean = mean;
    }
    @Override
    public String toString() {
        return "PersonVO [firstName=" + firstName + ", lastName=" + lastName
                + ", mean=" + mean + "]";
    }


}

以下是比较器的实现

import java.util.Comparator;


    public class PersonComparator implements Comparator<PersonVO> {

        @Override
        public int compare(PersonVO p1, PersonVO p2) {
            return Double.valueOf(p1.getMean()).compareTo(Double.valueOf(p2.getMean()));
        }

    }