如何对Java数据集进行排序

时间:2014-04-17 13:04:48

标签: java arrays class sorting

我这里有一些数据

 VAN,Ford,Transit,7995
 VAN,Ford,Transit,8900
 VAN,Ford,Transit,6200

我已经分割了数据,但我需要先从最便宜的面包车订购,我不知道从哪里开始。到目前为止,这是我的代码:

import java.io.BufferedReader;
import java.io.FileReader;


public class Vehicle {
    public static void main(String[]args) throws Exception
    {
        FileReader file = new FileReader("C:/Users/Aaron/Documents/java/car_file.txt");
        BufferedReader reader = new BufferedReader(file);
        String text = "";
        String line = reader.readLine();
        while (line!= null)
        {
            text += line+"\r\n";
            line = reader.readLine();
        }

        System.out.println(text);       
    }
}

我猜你上课并对数据进行排序,但我不知道从哪里开始。

5 个答案:

答案 0 :(得分:0)

我建议为包含合适成员的车辆创建一个类,在您的情况下为String类型和int类型中的三个,这将是Price。然后将为从文本文件读取的每一行生成一个新实例,填充成员。应将新实例放入容器中。您还必须实现一个可以决定实例顺序的比较器 - 在您的情况下,它会检查两个实例的Price并返回差异。

答案 1 :(得分:0)

以下是我使用可比较的

找到的示例
     public class Employee implements Comparable {

int EmpID;
String Ename;
double Sal;
static int i;

public Employee() {
    EmpID = i++;
    Ename = "dont know";
    Sal = 0.0;
}

public Employee(String ename, double sal) {
    EmpID = i++;
    Ename = ename;
    Sal = sal;
}

public String toString() {
    return "EmpID " + EmpID + "\n" + "Ename " + Ename + "\n" + "Sal" + Sal;
}

public int compareTo(Object o1) {
    if (this.Sal == ((Employee) o1).Sal)
        return 0;
    else if ((this.Sal) > ((Employee) o1).Sal)
        return 1;
    else
        return -1;
}

}

和测试类

     import java.util.*;

public class ComparableDemo {

public static void main(String[] args) {

    List ts1 = new ArrayList();
    ts1.add(new Employee ("Tom",40000.00));
    ts1.add(new Employee ("Harry",20000.00));
    ts1.add(new Employee ("Maggie",50000.00));
    ts1.add(new Employee ("Chris",70000.00));
    Collections.sort(ts1);
    Iterator itr = ts1.iterator();

    while(itr.hasNext()){
        Object element = itr.next();
        System.out.println(element + "\n");

    }

}

}

<强>输出

EmpID 1 哈利 Sal20000.0

EmpID 0 驯服汤姆 Sal40000.0

EmpID 2 Ename Maggie Sal50000.0

EmpID 3 让克里斯 Sal70000.0

答案 2 :(得分:0)

对于初学者,让我们将您文件中的行解析为Car对象,而不是将它们放在一个大字符串中:

public static void main(String[]args) throws Exception
{
    FileReader file = new FileReader("C:/Users/Aaron/Documents/java/car_file.txt");
    BufferedReader reader = new BufferedReader(file);
    List<Car> cars = new ArrayList<Car>();
    String line = reader.readLine();
    while (line!= null)
    {
        cars.add(new Car(line));
        line = reader.readLine();
    }
}

public class Car {
    private String type;
    private String brand;
    private String model;
    private int price;

    public Car(String spec) {
        String[] parts = spec.split(",");
        if (parts == null || parts.length != 4) {
            throw new IllegalArgumentException("Bad car specification: " + spec);
        }
        int i = 0;
        type = parts[i++];
        brand = parts[i++];
        model = parts[i++];
        price = Integer.parseInt(parts[i++]);
   }

   public int getPrice() {
        return price;
   }

   // other getters and setters could go here

   public String toString() {
       return String.format("Car type=%s, brand=%s, model=%s, price=%s", type, brand, model, price);
    }
}

现在我们需要对它们进行排序。一种方法是实现Comparator。其中一个答案描述了通过让Car类实现Comparable来实现此目的的另一种方法。我没有选择该解决方案的原因是它只允许一个汽车排序。如果您以后希望能够按其他方式进行排序,那么使用Comparable是不可能的。因此,使用单独的比较器会更松散地耦合,从而提供更大的灵活性。

如果你看一下Comparator的比较方法的JavaDoc(参见上面的链接),它会说:

  

比较其订单的两个参数。返回负整数,零或正数   第一个参数的整数小于,等于或大于第二个参数。

因此,如果第一个参数小于第二个参数,我们必须返回一个负整数:

public class CarPriceComparator implements Comparator<Car> {
    @Override
    public int compare(Car o1, Car o2) {
        return o1.getPrice() - o2.getPrice();
    }
}

现在您可以对汽车列表进行排序,例如致电Collections.sort

Collections.sort(cars, new CarPriceComparator());

打印结果:

for(Car car : cars) {
    System.out.println(car);
}

注意:我在Car中实现了toString,否则上面的代码只会打印汽车的对象引用。

答案 3 :(得分:0)

试试这个:

经过测试和执行。为了实现这一点,如果你敏锐地观察,line.split(",")[3];扮演关键角色。

import java.io.*;
import java.util.*;

public class ArrageItInOrder{

    public static void main(String[] args) throws Exception {
        System.out.println(System.getProperty("user.dir"));
        String filePath="C:/Users/Aaron/Documents/java/car_file.txt";
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        Map<String, String> map=new TreeMap<String, String>();
        String line="";
        while((line=reader.readLine())!=null){
            map.put(getField(line),line);
        }
        reader.close();
        FileWriter writer = new FileWriter(filePath);
        for(String val : map.values()){
            writer.write(val);  
            writer.write('\n');
        }
        writer.close();
    }

    private static String getField(String line) {
        return line.split(",")[3];//extract value you want to sort on
    }
}

答案 4 :(得分:0)

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;

class Vehicle implements Comparable<Vehicle>{
    private final String type;
    private final String manufacturer;
    private final String model;
    private final int number;

    public static void main(String[] args) throws Exception {
        FileReader file = new FileReader("C:/Users/Aaron/Documents/java/car_file.txt");
        BufferedReader reader = new BufferedReader(file);
        String line;
        String[] fields;
        ArrayList<Vehicle> vehicleList = new ArrayList<Vehicle>();
        while ((line=reader.readLine()) != null) {
            fields=line.split(",");
            vehicleList.add(new Vehicle(fields[0], fields[1], fields[2], Integer.parseInt(fields[3])));
        }
        Collections.sort(vehicleList);
        for (Vehicle v : vehicleList) {
            System.out.println(v);
        }
    }

    public Vehicle(String type, String manufacturer, String model, int number) {
        this.type = type;
        this.manufacturer = manufacturer;
        this.model = model;
        this.number = number;
    }

    @Override
    public int compareTo(Vehicle other) {
        int comparison = this.type.compareTo(other.type);
        if (comparison == 0) comparison=this.manufacturer.compareTo(other.manufacturer);
        if (comparison == 0) comparison=this.model.compareTo(other.model);
        if (comparison == 0) comparison=this.number-other.number;
        return comparison;        
    }

    @Override
    public String toString() {
        return type+","+manufacturer+","+model+","+number;
    }
}