Java - 按文件中的字符串属性对 ArrayList 进行排序 [英] Java - Sorting ArrayList by string attribute from file
问题描述
这就是我一整天都在努力实现的目标.我目前有一个类,它具有我的对象的属性,带有 setter 和 getter.我有另一个类,我在其中读取我的 CSV 文件并将其放入 ArrayList 中.文件的每一行都是一个对象,每一列都是我分配的属性,这在我执行 System.out.println 时有效.
Here is what I have been trying to achieve the whole day. I currently have a class which has the attributes for my objects with setters and getters. I have another class where I read my CSV file and put it in a ArrayList. Every row of the file is a object and every column is a attribute which I have assigned and this works when I do a System.out.println.
我现在想要的是创建一个类,该类可以按字符串属性对对象进行排序.我一整天都在尝试使用比较器,但我不知道自己在做什么.
What I now want to is create a class that can sort the objects by an attribute which is a string. How do I go about to do this as I have been trying all day using Comparators but I have no idea what I am doing.
推荐答案
假设您有一个这样的 CSV 文件:
Lets say you have a CSV file like this:
John,Smith,28
Jane,Doe,37
等等,那么我们就有了一个class Person
,比如:
Etc, then we have a class Person
, something like:
public class Person {
private String firstName;
private String lastName;
private int age;
//getters and setters
//equals and hashCode
}
然后我们将文件逐行读入List
.我们现在要按 lastName
对 List
进行排序.可以这样做:
We then read the file, line by line, into a List<Person>
. We now want to sort the List
by lastName
. This can be done like so:
final List<Person> people = readFile();
people.sort(Comparator.comparing(Person::getLastName));
这篇关于Java - 按文件中的字符串属性对 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!