问题
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.
回答1:
Lets say you have a CSV file like this:
John,Smith,28
Jane,Doe,37
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
}
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));
来源:https://stackoverflow.com/questions/28530443/java-sorting-arraylist-by-string-attribute-from-file