首页 > 解决方案 > 将 Collections.sort() 与具有多个变量的对象数组列表一起使用

问题描述

Collections.sort() 是否可以在 Car 对象数组列表中按 Make 进行排序?在那里添加空值后,我没有收到任何错误消息,但我的目标是具体按 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);
         }

标签: javasorting

解决方案


使用流式 API:

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

推荐阅读