如何将两个不同的List对象合并到一个List中并对它们进行排序

时间:2017-10-14 18:37:28

标签: java

我想将两个不同的List对象合并到另一个List中,我必须对它们进行排序。 我有类似下面的课程

类Employee和Class Staff这两个类根据时间戳实现Comparable和排序,这是一个很长的值

List<Employee> empList=new ArrayList<>();
    List<Staff> staffList=new ArrayList<>();
    Employee emp1=new Employee(3, "EPPI CF", 1507542925000l);
    Employee emp2=new Employee(2, "EPPI CF2", 1507542924000l);
    Employee emp3=new Employee(1, "EPPI CF3", 1507543156000l);
    empList.add(emp1);
    empList.add(emp2);
    empList.add(emp3);
    Collections.sort(empList);
    Staff staff1=new Staff(1, "Parnamya", 1507724760000l);
    Staff staff2=new Staff(2, "Sreenu", 1507623378000l);
    Staff staff3=new Staff(3, "Joseph", 1507621774000l);
    Staff staff4=new Staff(4, "Dolores", 1507547700000l);
    Staff staff5=new Staff(5, "Molly", 1507541100000l);
    staffList.add(staff1);
    staffList.add(staff2);
    staffList.add(staff3);
    staffList.add(staff4);
    staffList.add(staff5);
    Collections.sort(staffList);
    List<Object> allObj=new ArrayList<>();
    allObj.addAll(empList);
    allObj.addAll(staffList);

我想在对象common property是timestamp的两个对象中基于timestamp(long值)对allObj进行排序。

我该怎么做?

预期产出:

[Staff [id=1, staffName=Parnamya, timestamp=1507724760000],
Staff [id=2, staffName=Sreenu, timestamp=1507623378000], 
Staff [id=3, staffName=Joseph, timestamp=1507621774000],
Staff [id=4, staffName=Dolores,timestamp=1507547700000],
[
    Employee [id=1, name=EPPI CF3, timstamp=1507543156000], 
    Employee [id=3, name=EPPI CF, timstamp=1507542925000], 
    Employee [id=2, name=EPPI CF2, timstamp=1507542924000],
    Staff [id=5, staffName=Molly, timestamp=1507541100000]
]

1 个答案:

答案 0 :(得分:4)

您需要使它们扩展相同的超类或实现相同的接口进行比较。让它们扩展如下所示的类应该可以工作:

public abstract class TimeStamped implements Comparable<TimeStamped>{

@Override
public int compareTo(TimeStamped timedObject) {
    return Long.compare(this.getTimeStamp(), timedObject.getTimeStamp());
}

public abstract long getTimeStamp();

}