【问题标题】:How to sort an ArrayList by a users last name如何按用户姓氏对 ArrayList 进行排序
【发布时间】:2015-02-17 14:44:57
【问题描述】:

如何按用户姓氏对ArrayList 进行排序?我的程序按名字顺序打印出名字。还有另一种collections.sort(..); 方法吗?或者不制作地图的方式。

public static void main(String[] args) throws FileNotFoundException {
    String check = "y";
    do {
        Scanner fileRead = new Scanner(System.in);
        System.out.println("Enter the name of the file: ");
        File myFile = new File(fileRead.next());
        ArrayList<String> names = new ArrayList<>();

        Scanner scanTwo = new Scanner(myFile);

        while (scanTwo.hasNextLine()) {
            names.add(scanTwo.nextLine());
        }
        Collections.sort(names);
        for (String name : names) {
            System.out.println(name);
        }

        System.out.println();
        Scanner ans = new Scanner(System.in);
        System.out.println("Add another? y/n ");
        check = ans.next();
    } while (check.equals("y"));
} 

【问题讨论】:

  • 您需要创建一个自定义比较器,它会覆盖 compare(),然后比较姓氏。然后通过将比较器传递给它来调用 Arrays.sort()。

标签: java sorting arraylist collections


【解决方案1】:

使用将实现Comparable&lt;Person&gt; 接口的 Person 类,例如:

public class Person implements Comparable<Person> {
    String fname;
    String lname;
    //getter setter
    public int compareTo(Person person) {
        int comparedFname = this.fname.compareTo(person.getFname());
        if (comparedFname == 0) {//if fname are same then compare by last name
            return this.lname.compareTo(person.getLname());
        }
        return comparedFname;
    }
}

然后您可以创建 Person 对象列表并使用Collections.sort 方法对您的列表进行排序。

【讨论】:

  • 您也可以使用Collections.sort(List&lt;T&gt; list, Comparator&lt;? super T&gt; c),并传递一个Comparator,这样可以根据需要对列表进行不同的排序。
  • 同意。我给出了一个具体的实现。
猜你喜欢
  • 2020-11-03
  • 1970-01-01
  • 2019-05-06
  • 2015-07-08
  • 2020-09-10
  • 2015-05-25
  • 1970-01-01
  • 2021-01-04
  • 2013-11-03
相关资源
最近更新 更多