-5

I have Hashmap for example

Map<EmailCategoryModel, List<EmailBlogDetailsModel>> map;

how do I sort Map based on some property of key?

  • You want sort.. what? the map? sort the `List`? – David Pérez Cabrera Mar 28 '17 at 10:23
  • @DavidPérezCabrera, I want to sort map – Bajjuri Karthik Mar 28 '17 at 10:25
  • The only map that you can sort is a LinkedHashMap, by definition a map hasn't order. – David Pérez Cabrera Mar 28 '17 at 10:26
  • @DavidPérezCabrera A `LinkedHashMap` is not really sorted by a property, it just has the same order as the entries are putted in. – Stefan Warminski Mar 28 '17 at 10:29
  • 1
    I would use a `java.util.TreeMap`. Since your model does not implement `Comparable` you need to set a `Comparator`. – Stefan Warminski Mar 28 '17 at 10:31
  • @StefanWarminski You are right, but you can 'sort' it in this way: `Map> orderedMap = new LinkedHashMap<>(map.size()); map.entrySet().stream().sorted( (a, b) -> a.getKey().getProperty().compareTo(b.getKey().getProperty())).forEach(e -> orderedMap.put(e.getKey(), e.getValue()));` – David Pérez Cabrera Mar 28 '17 at 10:40
  • 1
    (source: [link](http://stackoverflow.com/questions/26902801/how-to-sort-hashmap-based-on-property-of-key-object-when-values-of-hashmap-are-s#comment42358548_26902801)) "It's generally best to avoid sorting a Mapping structure. The reason being is a map is supposed to be a lookup table. When finding a value, it takes O(1) time to look it up. There is no need to sort it. I would consider going with a different data structure if possible." – Pshemo Mar 28 '17 at 10:42

1 Answers1

0

Use TreeMap which is a sorted map and then use comparator or comparable interface. Code:

// Use TreeMap like this

TreeMap<EmailCategoryModel, EmailBlogDetailsModel> map = new TreeMap<>(new ComparatorNew());

// And create comparator somewhat like this
class ComparatorNew implements Comparator<EmailCategoryModel> {

    @Override
    public int compare(EmailCategoryModel o1, EmailCategoryModel o2) {
        // Do sorting based on your model attribute here.
        return 0;
    }

}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
DNAj
  • 240
  • 3
  • 9
  • 1
    Why `ComparatorNew` should extend `TreeMap`? – Stefan Warminski Mar 28 '17 at 10:46
  • By writing `class ComparatorNew` you are *declaring* two generic types named `EmailCategoryModel` and `EmailBlogDetailsModel`. So effectively your code can be rewritten as `class ComparatorNew implements Comparator` which doesn't look right since it doesn't handle already existing `EmailCategoryModel` type. You most likely wanted `class ComparatorNewimplements Comparator` – Pshemo Mar 28 '17 at 10:49
  • Agreed, Thanks @Pshemo – DNAj Mar 28 '17 at 10:53
  • It seems beside generic type declaration I also deleted `implements` keyword from last code example in my previous comment. Just add it before `Comparator` – Pshemo Mar 28 '17 at 10:56
  • I didnt delete that from example – DNAj Mar 28 '17 at 10:58