I am getting json
data as this:
[
{
"name": "A",
"count": "2"
},
{
"name": "B",
"count": "1"
},
{
"name": "A",
"count": "3"
},
{
"name": "C",
"count": "10"
},
{
"name": "B",
"count": "2"
}
]
So i iterate the data using a for
loop, normal stuff. But i would like to end up with an arraylist
like this:
C-->7
A-->5
B-->3
Notice that the the list
is ordered from the highest to the lowest.
What i have tried so far is:
//create my arraylists
//has both name and count
ArrayList<String>namesWithCountList = new ArrayList<>();
//has only names
ArrayList<String>namesList = new ArrayList<>();
//get json array..
//iterate using for loop
for (int i = 0; i < myJsonArray.length(); i++) {
String nameStr = jsonObj.getString("name");
int count = jsonObj.getInt("count");
index = namesList.indexOf(name);//get index of the name
if (index < 0) {
// name doesnt exist in namesList, so we add it
namesList.add(nameStr);
namesWithCountList.add(nameStr+"-->"+count);
}else{
//name exists so we only add the count to existing list
}
}
I know i should use Comparator.sort()
but i dont know how to get my list
there because i have mixed both the name and count together like: C-->7
I have been stressing out on how the logic should look like, any help on this?