将Collections.sort()与具有多个变量的对象数组列表一起使用

时间:2019-03-16 09:18:38

标签: java sorting

Collections.sort()是否可以在汽车对象数组列表中通过Make进行排序?在其中添加了null之后,我没有收到任何错误消息,但是我的目标是具体按照Make对其进行排序,但是我不完全确定该怎么做。

public void readingFromFile(String file) throws FileNotFoundException //an object array that takes in string files
         {  
            try {
                File myFile = new File(file); //converts the parameter string into a file
                Scanner scanner = new Scanner(myFile); //File enables us to use Scanner
                String line = scanner.nextLine(); //reads the current line and points to the next one
                StringTokenizer tokenizer = new StringTokenizer(line, ","); //tokenizes the line, which is the scanned file

                 //counts the tokens 
                while (tokenizer.hasMoreTokens()){
                    String CarMake = tokenizer.nextToken(); //since car is in order by make, model, year, and mileage
                    String CarModel = tokenizer.nextToken();
                    int CarYear1 = Integer.parseInt(tokenizer.nextToken());
                    int CarMileage1 = Integer.parseInt(tokenizer.nextToken()); //converts the String numbers into integers
                    Car cars = new Car(CarMake, CarModel, CarYear1, CarMileage1); //since the car has a fixed order 
                    arraylist.add(cars); //add the cars to the unsorted array
                }
              scanner.close(); //close the scanner  
            } catch (FileNotFoundException f){
                f.printStackTrace();
                return;
            }
            arraylist2.addAll(arraylist);
            Collections.sort(arraylist2, null);
         }

2 个答案:

答案 0 :(得分:0)

使用流式API:

sorted = arrayList2.stream().sorted(Comparator.comparing(Car::getMake));

答案 1 :(得分:0)

自Java 8以来,列表具有Collection继承的sort方法。另外,您可以使用Comparator类非常容易地创建比较器:

arraylist2.sort(Comparator.comparing(Car::getMake));

如果要使用多个参数进行排序,则可以轻松地附加它们:

arraylist2.sort(Comparator.comparing(Car::getMake)
    .thenComparing(Car::getYear)
    // ...
);

如果您使用的是Java 8以下的Java版本,则必须自己在比较器中实现排序逻辑或使用外部库:

Collections.sort(arraylist2, new Comparator<Car>() {
    @Override
    public int compare(Car a, Car b) {
        return a.getMake().compareTo(b.getMake());
    }
});

对于多个参数,其外观如下:

Collections.sort(arraylist2, new Comparator<Car>() {
    @Override
    public int compare(Car a, Car b) {
        int compareMake = a.getMake().compareTo(b.getMake());
        if (compareMake != 0) {
            return compareMake;
        }
        return a.getYear() - b.getYear();
    }
});