[英]how to merge two different List objects into one List and sort them
我想将两个不同的List对象合并到另一个List中,我必须对它们进行排序。 我有下面的课程
Employee和Class Staff类都基于时间戳(长值)实现Comparable和sorting
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);
我想基于两个对象的通用属性为时间戳,基于时间戳(长值)对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]
]
您需要使它们扩展相同的超类或实现相同的接口进行比较。 让它们都扩展如下所示的类应该起作用:
public abstract class TimeStamped implements Comparable<TimeStamped>{
@Override
public int compareTo(TimeStamped timedObject) {
return Long.compare(this.getTimeStamp(), timedObject.getTimeStamp());
}
public abstract long getTimeStamp();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.