Java - Sorting ArrayList by string attribute from file [closed]

[亡魂溺海] 提交于 2019-12-25 17:44:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!