对象的数组
Statement:[
{
"date": "12-09-19 11:02:47",
"Country": "Bangladesh",
"Profession": "X",
"Salary": "100",
},
{
"date": "12-09-19 11:02:47",
"Country": "Bangladesh",
"Profession": "Y",
"Salary": "101",
},
{
"date": "12-09-19 11:02:47",
"Country": "Bangladesh",
"Profession": "Z",
"Salary": "102",
},
{
"date": "11-09-19 11:02:47",
"Country": "India",
"Profession": "I",
"Salary": "103",
},
{
"date": "11-09-19 11:02:47",
"Country": "India",
"Profession": "J",
"Salary": "104",
},
{
"date": "10-09-19 11:02:47",
"Country": "Nepal",
"Profession": "N",
"Salary": "105",
},
{
"date": "10-09-19 11:02:47",
"Country": "Nepal",
"Profession": "M",
"Salary": "106",
}
]
我正在尝试创建一个新的数组
,它将创建一个对象
,其中每个日期(作为键)和同一对象中的其他信息
.
新数组应如下所示:
"10-09-19": [
{
"Country": "Nepal",
"Profession": "M",
"Salary": "106",
},
{
"Country": "Nepal",
"Profession": "N",
"Salary": "105",
}
],
"11-09-19": [{
"Country": "India",
"Profession": "J",
"Salary": "104",
},
{
"Country": "India",
"Profession": "I",
"Salary": "103",
}
],
"12-09-19": [{
"Country": "Bangladesh",
"Profession": "x",
"Salary": "104",
},
{
"Country": "Bangladesh",
"Profession": "y",
"Salary": "103",
},
{
"Country": "Bangladesh",
"Profession": "z",
"Salary": "102",
}
]
最佳答案
使用 hashmap 来存储数据日期。 HashMap 的键将是日期。 这是我的代码,它可能会帮助您理解逻辑。
var sortedList= HashMap<String, MutableList<Model>>() // create hashmap to store data
var temp: MutableList<Model>? = ArrayList<Model>()
for (item in currentList!!) {
temp = sortedList?.get(item.date.split(" ").get(0)) // get date and remove timing
if (temp != null) //if this is not null it mean this contain items
temp.add(item)
else {
temp = ArrayList<Model>() //if this is null it means this is new data or new data
temp.add(item)
}
sortedList?.put(item.date.split(" ").get(0), temp)
}
我的代码是用 kotlin 编写的,对此深表歉意。 快乐编码。
关于java - 在Android中,我如何按日期对数组项进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58265240/