java - 将 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);
}
解决方案
使用流式 API:
sorted = arrayList2.stream().sorted(Comparator.comparing(Car::getMake));
推荐阅读
- javascript - 如何编辑选定的 html 列?
- html - 在我的站点中,自动换行符不适用于 mathjax,但在任何在线 mathjax 现场演示中测试的相同方程都可以正常工作
- javascript - 检查字符串是否包含链接 javascript
- windows - 缺少从 zip 安装的 Perl 模块
- android - Android - 无法按预期设置按钮边框
- sql - 如何在sql中查询项目最大日期的前一个日期,如果项目只有一个日期,则返回该日期作为结果
- java - java中如何打印出树形结构的父子节点?
- c# - elasticsearch在NEST中空格字符后第一次搜索没有找到结果
- html - 在背景颜色之上覆盖 PNG。目标 - 在部分之间创建过渡
- tensorflow-lite - 有没有人想在windows的tensorflow Lite下编译demo