如何按某些属性对对象列表进行排序

时间:2011-04-27 14:18:12

标签: java sorting

我有简单的课程

public class ActiveAlarm {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;
}

List<ActiveAlarm>骗局如何按timeStarted按升序排序,然后按timeEnded按升序排序?有人可以帮忙吗?我在C ++中知道通用算法和重载运算符&lt;,但我是Java的新手。

15 个答案:

答案 0 :(得分:133)

使ActiveAlarm实施Comparable<ActiveAlarm>或在单独的班级中实施Comparator<ActiveAlarm>。然后致电:

Collections.sort(list);

Collections.sort(list, comparator);

一般来说,如果只有一个“自然”排序顺序,那么实施Comparable<T>是个好主意...否则(如果你发生想按特定顺序排序,但同样可能很容易想要一个不同的)最好实现Comparator<T>。这种特殊情况可以是任何一种方式,说实话......但我可能坚持使用更灵活的Comparator<T>选项。

编辑:示例实施:

public class AlarmByTimesComparer implements Comparator<ActiveAlarm> {
  @Override
  public int compare(ActiveAlarm x, ActiveAlarm y) {
    // TODO: Handle null x or y values
    int startComparison = compare(x.timeStarted, y.timeStarted);
    return startComparison != 0 ? startComparison
                                : compare(x.timeEnded, y.timeEnded);
  }

  // I don't know why this isn't in Long...
  private static int compare(long a, long b) {
    return a < b ? -1
         : a > b ? 1
         : 0;
  }
}

答案 1 :(得分:109)

使用Comparator

例如:

class Score {

    private String name;
    private List<Integer> scores;
    // +accessor methods
}

    Collections.sort(scores, new Comparator<Score>() {

        public int compare(Score o1, Score o2) {
            // compare two instance of `Score` and return `int` as result.
            return o2.getScores().get(0).compareTo(o1.getScores().get(0));
        }
    });

使用Java 8以后,您只需使用lambda表达式来表示Comparator实例。

Collections.sort(scores, (s1, s2) -> { /* compute and return int */ });

答案 2 :(得分:37)

JAVA 8及以上答案(使用Lambda表达式)

在Java 8中,引入了Lambda表达式以使其更容易!您可以按如下方式简化它,而不是使用所有脚手架创建Comparator()对象:(以您的对象为例)

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.timeStarted-a2.timeStarted);

甚至更短:

Collections.sort(list, Comparator.comparingInt(ActiveAlarm ::getterMethod));

这一句话相当于以下内容:

Collections.sort(list, new Comparator<ActiveAlarm>() {
    @Override
    public int compare(ActiveAlarm a1, ActiveAlarm a2) {
        return a1.timeStarted - a2.timeStarted;
    }
});

将Lambda表达式想象成只需要输入代码的相关部分:方法签名和返回的内容。

您问题的另一部分是如何与多个字段进行比较。要使用Lambda表达式执行此操作,您可以使用.thenComparing()函数将两个比较有效地合并为一个:

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.timeStarted-a2.timeStarted             
       .thenComparing ((ActiveAlarm a1, ActiveAlarm a2) -> a1.timeEnded-a2.timeEnded)
);

上述代码将首先按timeStarted对{4}进行排序,然后按timeEndedtimeStarted的记录进行排序。

最后一点:很容易比较'long'或'int'原语,你可以从另一个中减去一个。如果您要比较对象('Long'或'String'),我建议您使用它们的内置比较。例如:

Collections.sort(list, (ActiveAlarm a1, ActiveAlarm a2) -> a1.name.compareTo(a2.name) );
编辑:感谢Lukas Eder指导我.thenComparing()功能。

答案 3 :(得分:19)

我们可以通过以下两种方式之一对列表进行排序:

<强> 1。使用Comparator :当需要在多个位置使用排序逻辑时 如果你想在一个地方使用排序逻辑,那么你可以按如下方式编写一个匿名内部类,或者提取比较器并在多个地方使用它

  Collections.sort(arrayList, new Comparator<ActiveAlarm>() {
        public int compare(ActiveAlarm o1, ActiveAlarm o2) {
            //Sorts by 'TimeStarted' property
            return o1.getTimeStarted()<o2.getTimeStarted()?-1:o1.getTimeStarted()>o2.getTimeStarted()?1:doSecodaryOrderSort(o1,o2);
        }

        //If 'TimeStarted' property is equal sorts by 'TimeEnded' property
        public int doSecodaryOrderSort(ActiveAlarm o1,ActiveAlarm o2) {
            return o1.getTimeEnded()<o2.getTimeEnded()?-1:o1.getTimeEnded()>o2.getTimeEnded()?1:0;
        }
    });

如果我们可以使用'Long'而不是'long',我们可以对属性进行空检查。

<强> 2。使用Comparable(自然排序):如果排序算法始终坚持一个属性: 编写一个实现'Comparable'的类并覆盖'compareTo'方法,如下所述

class ActiveAlarm implements Comparable<ActiveAlarm>{

public long timeStarted;
public long timeEnded;
private String name = "";
private String description = "";
private String event;
private boolean live = false;

public ActiveAlarm(long timeStarted,long timeEnded) {
    this.timeStarted=timeStarted;
    this.timeEnded=timeEnded;
}

public long getTimeStarted() {
    return timeStarted;
}

public long getTimeEnded() {
    return timeEnded;
}

public int compareTo(ActiveAlarm o) {
    return timeStarted<o.getTimeStarted()?-1:timeStarted>o.getTimeStarted()?1:doSecodaryOrderSort(o);
}

public int doSecodaryOrderSort(ActiveAlarm o) {
    return timeEnded<o.getTimeEnded()?-1:timeEnded>o.getTimeEnded()?1:0;
}

}

调用sort方法根据自然排序进行排序

Collections.sort(list);

答案 4 :(得分:4)

public class ActiveAlarm implements Comparable<ActiveAlarm> {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;

    public int compareTo(ActiveAlarm a) {
        if ( this.timeStarted > a.timeStarted )
            return 1;
        else if ( this.timeStarted < a.timeStarted )
            return -1;
        else {
             if ( this.timeEnded > a.timeEnded )
                 return 1;
             else
                 return -1;
        }
 }

那应该给你一个粗略的想法。完成后,您可以在列表中调用Collections.sort()

答案 5 :(得分:4)

在java8 +中,这可以用单行写成,如下所示,

collectionObjec.sort(comparator_lamda)或comparator.comparing(CollectionType :: getterOfProperty)

代码:

ListOfActiveAlarmObj.sort((a,b->a.getTimeStarted().compareTo(b.getTimeStarted())))

ListOfActiveAlarmObj.sort(Comparator.comparing(ActiveAlarm::getTimeStarted))

答案 6 :(得分:2)

自Java8以来,使用ComparatorLambda expressions

的组合可以做得更干净

例如:

class Student{

    private String name;
    private List<Score> scores;

    // +accessor methods
}

class Score {

    private int grade;
    // +accessor methods
}
    Collections.sort(student.getScores(), Comparator.comparing(Score::getGrade);

答案 7 :(得分:1)

Guava的ComparisonChain

Collections.sort(list, new Comparator<ActiveAlarm>(){
            @Override
            public int compare(ActiveAlarm a1, ActiveAlarm a2) {
                 return ComparisonChain.start()
                       .compare(a1.timestarted, a2.timestarted)
                       //...
                       .compare(a1.timeEnded, a1.timeEnded).result();
            }});

答案 8 :(得分:1)

在java中,您需要使用静态Collections.sort方法。以下是CompanyRole对象列表的示例,首先按开始然后按结束排序。您可以轻松适应自己的对象。

private static void order(List<TextComponent> roles) {

    Collections.sort(roles, new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            int x1 = ((CompanyRole) o1).getBegin();
            int x2 = ((CompanyRole) o2).getBegin();

            if (x1 != x2) {
                return x1 - x2;
            } else {
                int y1 = ((CompanyRole) o1).getEnd();
                int y2 = ((CompanyRole) o2).getEnd();
                return y2 - y1;
            }
        }
    });
}

答案 9 :(得分:1)

使用 Stream API 的 Java-8 解决方案:

A.timeStartedtimeEndedpublic 时(如要求中所述),因此不(需要)有 {{1} } 获取方法:

public

B.List<ActiveAlarm> sorted = list.stream() .sorted(Comparator.comparingLong((ActiveAlarm alarm) -> alarm.timeStarted) .thenComparingLong((ActiveAlarm alarm) -> alarm.timeEnded)) .collect(Collectors.toList()); timeStartedtimeEnded 的 getter 方法时:

public

如果要对原始 List<ActiveAlarm> sorted = list.stream() .sorted(Comparator.comparingLong(ActiveAlarm::getTimeStarted) .thenComparingLong(ActiveAlarm::getTimeEnded)) .collect(Collectors.toList()); 本身进行排序:

A.listtimeStartedtimeEnded 时(如要求中所述),因此不(需要)有 {{1} } 获取方法:

public

B.publiclist.sort(Comparator.comparingLong((ActiveAlarm alarm) -> alarm.timeStarted) .thenComparingLong((ActiveAlarm alarm) -> alarm.timeEnded)); timeStarted 的 getter 方法时:

timeEnded

答案 10 :(得分:1)

我们可以使用 Comparator.comparing() 方法根据对象的属性对列表进行排序。

class SortTest{
    public static void main(String[] args) {
        ArrayList<ActiveAlarm> activeAlarms = new ArrayList<>(){{
            add(new ActiveAlarm("Alarm 1", 5, 10));
            add(new ActiveAlarm("Alarm 2", 2, 12));
            add(new ActiveAlarm("Alarm 3", 0, 8));
        }};

        /* I sort the arraylist here using the getter methods */
        activeAlarms.sort(Comparator.comparing(ActiveAlarm::getTimeStarted)
                .thenComparing(ActiveAlarm::getTimeEnded));

        System.out.println(activeAlarms);
    }
}

请注意,在执行此操作之前,您必须至少定义要作为排序依据的属性的 getter 方法。

public class ActiveAlarm {
    public long timeStarted;
    public long timeEnded;
    private String name = "";
    private String description = "";
    private String event;
    private boolean live = false;

    public ActiveAlarm(String name, long timeStarted, long timeEnded) {
        this.name = name;
        this.timeStarted = timeStarted;
        this.timeEnded = timeEnded;
    }

    public long getTimeStarted() {
        return timeStarted;
    }

    public long getTimeEnded() {
        return timeEnded;
    }

    @Override
    public String toString() {
        return name;
    }
}

输出:

[Alarm 3, Alarm 2, Alarm 1]

答案 11 :(得分:0)

您可以调用Collections.sort()并传入一个Comparator,您需要编写该Comparator来比较对象的不同属性。

答案 12 :(得分:0)

您可以使用Collections.sort并传递自己的Comparator<ActiveAlarm>

答案 13 :(得分:0)

如前所述,您可以按以下方式排序:

  • 使您的对象实现Comparable
  • 或将Comparator传递给Collections.sort

如果同时执行这两项操作,则会忽略Comparable并使用Comparator。这有助于值对象具有自己的逻辑Comparable,这对于您的值对象是最合理的排序,而每个单独的用例都有自己的实现。

答案 14 :(得分:0)

员工 POJO 类

package in.ac.adit.oop.sort;

public class Employee {
    private int id;
    private String name;
    private String department;

    public int getId() {
        return id;
    }

    public Employee() {
        super();
    }

    public Employee(int id, String name, String department) {
        super();
        this.id = id;
        this.name = name;
        this.department = department;
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", department=" + department + "]";
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }
}

Employee 类来管理员工

package in.ac.adit.oop.sort;

import java.util.ArrayList;
import java.util.List;

    public class Example {
        public static void main(String[] args) {
    
            /*
             * Create 10 Employee Object
             */
            Employee emp1 = new Employee(1, "Nayan", "IT");
            Employee emp2 = new Employee(2, "Siddarth", "CP");
            Employee emp3 = new Employee(3, "Samarth", "AE");
            Employee emp4 = new Employee(4, "Bhavesh", "CV");
            Employee emp5 = new Employee(5, "Sam", "FT");
            Employee emp6 = new Employee(6, "Keyur", "IT");
            Employee emp7 = new Employee(7, "Bala", "ME");
            Employee emp8 = new Employee(8, "Mitul", "ME");
            Employee emp9 = new Employee(9, "Kamlesh", "EE");
            Employee emp10 = new Employee(10, "Piyush", "EE");
    
            /*
             * List of Employee Object
             */
            List<Employee> employeeList = new ArrayList<Employee>();
            employeeList.add(emp1);
            employeeList.add(emp2);
            employeeList.add(emp3);
            employeeList.add(emp4);
            employeeList.add(emp5);
            employeeList.add(emp6);
            employeeList.add(emp7);
            employeeList.add(emp8);
            employeeList.add(emp9);
            employeeList.add(emp10);
    
            CustomObjectSort customObjectSort = new CustomObjectSort();
            List<Employee> sortByDepartment = customObjectSort.sortByDepartment(employeeList);
    
            /*
             * Sorted By Department
             */
            for (Employee employee : sortByDepartment) {
                System.out.println(employee);
            }
    
            /*
             * Sorted By Name
             */
            List<Employee> sortByName = customObjectSort.sortByName(employeeList);
    
            for (Employee employee : sortByName) {
                System.out.println(employee);
            }
    
            /*
             * Sorted By Id
             */
            List<Employee> sortById = customObjectSort.sortById(employeeList);
    
            for (Employee employee : sortById) {
                System.out.println(employee);
            }
    
        }
    }

自定义排序

package in.ac.adit.oop.sort;


import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CustomObjectSort {

    public List<Employee> sortByName(List<Employee> employeeList) {

        Collections.sort(employeeList, new Comparator<Employee>() {

            @Override
            public int compare(Employee employee1, Employee employee2) {
                return employee1.getName().compareTo(employee2.getName());
            }

        });
        return employeeList;
    }

    public List<Employee> sortByDepartment(List<Employee> employeeList) {

        Collections.sort(employeeList, new Comparator<Employee>() {

            @Override
            public int compare(Employee employee1, Employee employee2) {
                return employee1.getDepartment().compareTo(employee2.getDepartment());
            }

        });
        return employeeList;
    }

    public List<Employee> sortById(List<Employee> employeeList) {

        Collections.sort(employeeList, new Comparator<Employee>() {

            @Override
            public int compare(Employee employee1, Employee employee2) {
                return employee1.getId() - employee2.getId();
            }

        });
        return employeeList;
    }

}