我的情况是这样的:我有两个具有不同类型对象的数组列表。每个对象都有一个字段名称和一个字段日期 ArrayList 事件,ArrayList 事物。我按名称对数组列表进行排序,如果名称相同,则按日期排序。
假设 ArrayList1 具有以下对象:event1 01.12、event1 05.12、event2 04.03、event3 05.05
并且 ArrayList2 具有:event0 02.01,event2 05.10
现在我想创建一个 TableRow,其中包含一个带有事件名称的 TextView 和另一个带有事件日期的 TextView 。 所以我的表格布局将是这样的:
Event0 02.11(from2)
Event1 01.12(from1), 05.12(from1)
Event2 02.01(from2), 04.03(from1)
Event3 05.10(from1)
如何迭代 2 个数组列表并获取每个唯一事件及其所有日期以显示在 TableRow 中?
我这样排序
Collections.sort(alist, new Comparator<Object1>() {
@Override
public int compare(Object1 a1, Object1 a2) {
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Date date1;
Date date2;
if(a1.name.equals(a2.name)) {
try {
date1 = format.parse(a1.date);
date2 = format.parse(a2.date);
} catch (ParseException e) {
throw new IllegalArgumentException("Could not parse date!", e);
}
return date1.compareTo(date2);
}
else
return a1.name.compareTo(a2.name) ;
}
});
最佳答案
最好的方法是让不同类型的对象继承同一个类/实现相同的接口(interface)。如果这不可能,请尝试以下操作:
List<Object> combinedList = new ArrayList<>();
combinedList.addAll(array1);
combinedList.addAll(array2);
Collections.sort(combinedList, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
String name1 = o1 instanceof Type1 ? ((Type1) o1).getName()
: ((Type2) o1).getName();
String name2 = o2 instanceof Type1 ? ((Type1) o2).getName()
: ((Type2) o2).getName();
Date date1 = o1 instanceof Type1 ? ((Type1) o1).getDate()
: ((Type2) o1).getDate();
Date date2 = o2 instanceof Type1 ? ((Type1) o2).getDate()
: ((Type2) o2).getDate();
int comparedNames = name1.compareTo(name2);
return comparedEvents != 0 ? comparedEvents : date1.compareTo(date2);
}
});
关于java - 迭代并组合两个不同对象的排序数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28323233/