-4

I want to sort the complete map in descending order, the stucture of the map is below

SortedMap<String, SortedMap<String, Long>>

I want to sort by the Long value of the inner SortedMap. How can this be done?

Thank you.
EDIT: map changed to SortedMap
the Inner map will always contain a single value .

Mizan
  • 450
  • 1
  • 5
  • 28

1 Answers1

3

A HashMap can't be sorted. A TreeMap is sorted, but by keys, and not by values.

If you want to iterate over the entries of the map, sorted by their value, then I would simply copy all the entries to a list, sort this list as you want to, and iterate through the sorted list.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • but this will sort only the inner map .. I need to sort the complete inner + outer map based on the value of the inner map . if the sorting is incorrect the data will be displayed incorrectly – Mizan May 20 '13 at 10:15
  • That's not what you asked. You asked: I want to sort a nested map. Sorting the outer map doesn't make any sense. What if the inner map has several values (as any map typically has)? How to sort the entries, then? Anyway, the answer is the same. Extract the entries to a list and sort the list in whatever way you want. Instead of sorting a `List>`, you would sort a `List>>`. – JB Nizet May 20 '13 at 10:18
  • the inner map has only a single value (This cannot increase) . I need to sort the complete map. – Mizan May 20 '13 at 10:25
  • Then you have a serious design problem. Don't use a HashMap to hold a key and a value. Use a class, with 2 attributes. My answer still stands, though: extract the entries to a list, and sort the list. – JB Nizet May 20 '13 at 12:00
  • I use tree map and linked hashmap .and got the desired result .thanks for your support – Mizan May 23 '13 at 08:29
  • I also need to sort the map (TreeMap>) by inner map's values. can you please share the code? – gokul Feb 01 '16 at 20:18