Sorting in java for Map?

47 Views Asked by At

As we use Collections.sort(list) for Collection but can we able to use that in the case of map like by implementing Comparable and Comparator? Or we can just do iterator over a Map in java?

========================================================================

2

There are 2 best solutions below

0
On BEST ANSWER

An important feature of a list is that there is an order to the elements, whereas within a Map there is no such order. Therefore it doesn't make sense to sort a Map. If order is important to you, you really should be using a list.

0
On

For that purpose, we can use a treemap. Each entry we insert are automatically sorted

For the treemap to sort, you have to implement the comparable or comparator in the object(key) that you wish to put in treemap

Check out this link https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html