爪哇 - 从文件字符串属性排序的ArrayList [英] Java - Sorting ArrayList by string attribute from file
问题描述
这是我一直在努力实现的不亦乐乎。我现在有这对我的getter和setter方法的对象属性的类。我有另一个类,我读我的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
等等,然后我们有一个类Person
,是这样的:
public class Person {
private String firstName;
private String lastName;
private int age;
//getters and setters
//equals and hashCode
}
我们再读取该文件,一行行,成列表与LT;人>
。现在,我们希望通过的lastName
到列表
排序。这可以像这样做:
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));
这篇关于爪哇 - 从文件字符串属性排序的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!