简体   繁体   English

Java中按字母顺序排序列表

[英]Alphabetically sorting List in Java

I am new to Java and I have a question related to the following code(tried to find it on the internet but couldn't).我是 Java 新手,我有一个与以下代码相关的问题(试图在互联网上找到它但找不到)。 If I want to sort a List of Employee objects by their name in Java can I use the following approach?(found other approaches too but I'm interested in this one).如果我想在 Java 中按名称对 Employee 对象列表进行排序,我可以使用以下方法吗?(也找到了其他方法,但我对这个方法很感兴趣)。

    public class SortByName implements Comparator<Employee> {
        public int compare(Employee e1,Employee e2) {
            return e1.getName().compareTo(e2.getName());
        }
    } 

and somewhere in my main method the array of employees being empList, I could have:在我的主要方法中,员工数组是 empList,我可以:

Collections.sort(empList,new SortByName()); Collections.sort(empList,new SortByName());

? ? New to Java sorry if this is a stupid question.. Java 新手抱歉,如果这是一个愚蠢的问题..

This is a canonical example of sorting by comparator:这是按比较器排序的典型示例:

class Employee {
    private String name;
    ...
    public String getName() {
        return name;
    }
    ...
}
List<Employee> employees = ...
employees.sort(Comparator.comparing(Employee::getName));
System.out.println(employees); //prints out sorted list

In response to your query about your approach: yes, it's a valid approach.回应您对您的方法的询问:是的,这是一种有效的方法。 It compiles and runs correctly.它编译并正确运行。 However, it's generally used for cases where you have a very complex Comparator and feel the need to separate such logic into another class.但是,它通常用于您有一个非常复杂的 Comparator 并且觉得需要将此类逻辑分离到另一个类中的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM