Reputation: 475
I am getting response like this from server,
[
{
"id":"b2",
"type":"ball"
},
{
"id":"a1",
"type":"apple",
},
{
"id":"d4",
"type":"dog",
},
{
"id":"c3",
"type":"cat",
}
]
but I need to sort the above response data based on alphabets wise, based on "type". And then display the list, I am using model to parse the data .
Upvotes: 1
Views: 1635
Reputation: 75497
What data structure are you parsing the JSON into? If, for example, you have an Item
class similar to:
class Item {
Item(String id, String type) { ... }
String getType() { ... }
String getId() { ... }
}
And you parse that JSON into some kind of List<Item>
, then the following should work for sorting by type (API level 24+), see Comparator.comparing:
List<Item> items = ...; // however you parse the JSON
Comparator<Item> byType = Comparator.comparing(Item::getType);
Collection.sort(items, byType); // items will now be sorted
For a more general approach that will work with older API levels, you can define the byType
comparator like this:
Comparator<Item> byType = new Comparator<Item> {
public int compare(Item a, Item b) {
return a.getType().compareTo(b.getType());
}
};
Upvotes: 1
Reputation: 528
Convert it to an Object and implement Comparable<>
Interface. The use:
CompareTo()
Upvotes: 0
Reputation: 91
Json is an object is an unordered set of name/value pairs. See http://json.org. Convert to Object to sort.
Upvotes: 0
Reputation: 54
Can't you make your class Comparable and use :
type.compareTo()
In your own compareTo method in oder to be able to sort them by type?
Upvotes: 0