这是我的pojo课
inner class Data : Serializable {
var abc: ArrayList<ABC>? = null
var xyz: ArrayList<XYZ>? = null
inner class XYZ : Serializable {
var x: String? = null
var date: String? = null
}
inner class ABC : Serializable {
var a: String? = null
var date: String? = null
}
}
我想将ABC和XYZ数组列表合并到一个列表中,并根据日期对该列表进行排序
到目前为止,我已经完成了
val items = ArrayList<Any>()
items.addAll(data!!.xyz!!)
items.addAll(data!!.abc!!)
并获得这样的合并列表
x (from XYZ arraylist in descending order)
x (from XYZ arraylist in descending order)
x (from XYZ arraylist in descending order)
a (from ABC arraylist in descending order)
a (from ABC arraylist in descending order)
a (from ABC arraylist in descending order)
但是我想要的是根据日期对整个列表进行排序
答案 0 :(得分:1)
最好是引入一个WithDate
接口,让您的类实现它。
interface WithDate {
val date: String?
}
inner class XYZ : Serializable, WithDate {
var x: String? = null
override var date: String? = null
}
现在您有了WithDate
的列表,可以使用sortBy
函数了。
val list = ArrayList<WithDate>()
...
list.sortBy(WithDate::date)
如果您不能更改类,请执行以下操作:
val list = ArrayList<Any>()
list.sortBy {
when(it) {
is Data.XYZ -> it.date ?: ""
is Data.ABC -> it.date ?: ""
else -> ""
}
}
答案 1 :(得分:0)
您必须使用Collections.sort对列表进行排序。 步骤1: 合并列表时,请使用
Collections.sort(<UR LIST>, new compareMethod());
步骤2: 创建compareMethod();
class compareMethod implements Comparator<LISTNAME> {
@Override
public int compare(LISTNAME object1, LISTNAME object2) {
return object1.getDate().compareTo(object2.getDate());
}
}
希望您能理解
答案 2 :(得分:0)
请尝试以下方法。希望它能解决您的问题。
首先参加一个像下面这样的普通pojo课
class MergedResponse : Serializable {
var data: Data? = null
inner class Data : Serializable {
@SerializedName(value = "xyz", alternate = arrayOf("abc"))
var mCommon: ArrayList<Common>? = null
inner class Common : Serializable {
var x: String? = null
var a: String? = null
var date: String? = null
}
}
}
然后在您的课程中编写以下代码
val mainData = Gson().toJson(data!!)
var mJsonXYZ: JSONObject = JSONObject(mainData)
var mJsonABC: JSONObject = JSONObject(mainData)
mJsonXYZ.remove("abc")
mJsonABC.remove("xyz")
val mypojoXYZ = Gson().fromJson<MergedResponse.Data>(Gson().toJson(Gson().fromJson<Data>(mJsonXYZ.toString(), Data::class.java)), MergedResponse.Data::class.java)
val mypojoABC = Gson().fromJson<MergedResponse.Data>(Gson().toJson(Gson().fromJson<Data>(mJsonABC.toString(), Data::class.java)), MergedResponse.Data::class.java)
val itemsXYZ = ArrayList<MergedResponse.Data.Common>()
itemsXYZ.addAll(mypojoXYZ.mCommon!!)
itemsXYZ.addAll(mypojoABC.mCommon!!)
Collections.sort(itemsXYZ, object : Comparator<MergedResponse.Data.Common> {
override fun compare(object1: MergedResponse.Data.Common, object2: MergedResponse.Data.Common): Int {
return object1.date!!.compareTo(object2.date!!)
}
})