Kodali Kiran
Kodali Kiran

Reputation: 11

Sorting list of maps based on a value

I have a list of maps as follows

[[AdGenres-b:key:[177, 184],MusicalStyles-b:key:[30],SongTitle:[What I've Done],ArtistName:[LinkinPark],MusicVideoRating:[TV-14],MusicalStyles-b:value:[Rock],PlayId:[1367],AdGenres-b:value:[Rock - Rock, Rock - Alternative],MusicVideoProvider:[Warner Music Group], AssetId:[91744]],

[[AdGenres-b:key:[177, 184],MusicalStyles-b:key:[30],SongTitle:[What I've Done],ArtistName:[Linkin Park],MusicVideoRating:[TV-14], MusicalStyles-b:value:[Rock], PlayId:[1360], AdGenres-b:value:[Rock - Rock, Rock - Alternative], MusicVideoProvider:[Warner Music Group], AssetId:[91740]]

I want to sort the map by PlayId in ascending order and then store the sorted maps in a list. How can I achieve this?

Upvotes: 1

Views: 5059

Answers (3)

Deeraj Reddy
Deeraj Reddy

Reputation: 46

If all the Map are present in list, songs and if you don't want to use POJO entities.

List<Map<String, String>> songs = new ArrayList<>();

songs.add(new HashMap<String, String>() {{
    put("PlayId", "id3");
    put("Title", "title3");
}});

songs.add(new HashMap<String, String>() {{
    put("PlayId", "id2");
    put("Title", "title2");
}});

songs.add(new HashMap<String, String>() {{
    put("PlayId", "id5");
    put("Title", "title5");
}});

use java.util.List.sort(Comparator<? super Map<String, String>> c

To sort in ascending order,

songs.sort( (a,b) -> a.get("PlayId").compareTo(b.get("PlayId")) );

if in descending order,

songs.sort( (a,b) -> b.get("PlayId").compareTo(a.get("PlayId")) );

Also, we could use custom function for Comparator. if Comparator is null, then the natural order will be used

Upvotes: 0

Tahir Akhtar
Tahir Akhtar

Reputation: 11645

What you need a custom comparator.

Create a class that implements Comparator:

  class MyMapComparator {
    public int compare(Map m1, Map m2) {
      //get play id from both maps here and compare them
      return playId1 - playId2;
    }
  }

Then simply sort your list using instance of MyMapComparator.

Collections.sort(listTobeSorted, new MyMapComparator());

Upvotes: 0

aioobe
aioobe

Reputation: 421290

Implement your own Comparator<Map<Key, Value>> based on map.get("PlayId").

Example:

List<Map<String, String>> songs = new ArrayList<Map<String, String>>();

songs.add(new HashMap<String, String>() {{
    put("PlayId", "id3");
    put("Song Title", "some title");
}});

songs.add(new HashMap<String, String>() {{
    put("PlayId", "id5");
    put("Song Title", "some title");
}});

songs.add(new HashMap<String, String>() {{
    put("PlayId", "id2");
    put("Song Title", "some title");
}});

Collections.sort(songs, new Comparator<Map<String, String>>() {
    @Override
    public int compare(Map<String, String> o1, Map<String, String> o2) {
        return o1.get("PlayId").compareTo(o2.get("PlayId"));
    }
});

Upvotes: 3

Related Questions