How to sort map java
How to sort map java
How to sort a map
I have a Map to sort as follows:
It contains the following String keys:
It contains the following String values:
where the key and value can vary by their number of dot sections from key1/value1 to key1.key2.key3.key4.key5/value1.value2.value3.value4.value5 non-homogeneously
I need to compare them according to the number of dots present in keys or in values according to the calling method type key / value :
The methods of course will return a sorted map.
Any help would be appreciated.
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
If you want to order elements by some comparison on the keys, then use a TreeMap with some Comparator on the keys, or just use their default Comparable ordering.
So I’ll assume you’re using TreeMap, which is the canonical sorted map implementation. This sorts its keys according to a Comparator which you can supply in the constructor. So if you can write such a comparator that determines which is the «lower» of two arbitrary keys (spoiler alert: you can), this will be straightforward to implement.
This will, however, only work when sorting by key. I don’t know if it makes much sense to sort a map by value, and I’m not aware of any straightforward way to do this. The best I can think of is to write a Comparator that sorts on values, call Map.getEntrySet and push all the entries into a list, then call Collections.sort on the list. It’s not very elegant or efficient but it should get the job done if performance isn’t your primary concern.
(Note also that if your keys aren’t immutable, you will run into a lot of trouble, as they won’t be resorted when externally changed.
How to sort a Map in Java
September 10, 2019 • Atta ✨
In this short article, you will learn how to sort a Map in Java. This is probably one of the most frequently asked questions in Java interviews.
In Java, there are multiple ways to sort a Map, but we will focus on Java 8 Streams which is quite an elegant way of achieving this.
Java 8 Streams
The sorted() method takes a Comparator as a parameter, making it possible to sort the map by any type of value.
Sort By Keys
Here is an example that sorts the Map by keys using Java 8 streams:
The above program will print the following on the console:
If you want to sort the Map by keys in reserve order, you only need to change the comparing order to reverse like below:
Sort By Values
Off course, you can sort a Map by its values too using the Stream API:
Here is the output that shows the Map is sorted by values:
And if you want to sort the Map by values in descending order, just do the following:
Using TreeMap
The TreeMap class stores the keys in natural sorted order. It works perfect for sorting a Map by keys. All you need to do is create a TreeMap object, and push all the existing data from the HashMap into it:
Here is the output:
As you can see above, the keys (countries’ names) are sorted in a natural order.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
How to sort Map values by key in Java?
I have a Map that has strings for both keys and values.
Data is like following:
Eventually, I am trying to get two strings out of this Map.
Right now I have the following:
This gets me the questions in a string but they are not in order.
17 Answers 17
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Short answer
If this map is passed to you and you cannot determine the type, then you can do the following:
This will iterate across the map in natural order of the keys.
Longer answer
For cases where your keys are a complex type that doesn’t implement Comparable or you don’t want to use the natural order then TreeMap and TreeSet have additional constructors that let you pass in a Comparator :
Assuming TreeMap is not good for you (and assuming you can’t use generics):
Using the TreeMap you can sort the map.
Just use TreeMap
Be aware that the TreeMap is sorted according to the natural ordering of its ‘keys’
If you already have a map and would like to sort it on keys, simply use :
A complete working example :
Java 8 Example
We can modify the example to use custom comparator and to sort based on keys as:
Using Java 8:
In Java 8
To sort a Map by key, putting keys into a List :
To sort a Map by key, putting entries into a List > :
This code can sort a key-value map in both orders i.e. ascending and descending.
Just in case you don’t wanna use a TreeMap
Also, in-case you wanted to sort your map on the basis of values just change Map.Entry::getKey to Map.Entry::getValue
A good solution is provided here. We have a HashMap that stores values in unspecified order. We define an auxiliary TreeMap and we copy all data from HashMap into TreeMap using the putAll method. The resulting entries in the TreeMap are in the key-order.
How about below tree map:
What ever you put in this sortedMap it will be sorted automatically. First of all TreeMap is sorted implementation of Map Interface. There is a but as it sorts keys on [natural order fashion][https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html]. As Java doc says String type is a Lexicographic Natural order type. Imagine the below list of numbers with String type. means below list will be sorted not as expected.
List notSortedList = List.of(«78″,»0», «24», «39», «4»,»53″,»32″);
If you just you the default TreeMap constructor like below and push each element one-by-one like below:
As you see number 4 for example comes after ’39’. This is the nature of the Lexicographic data types like String. If that one was an Integer data type then that was okay though.
To fix this use argument to first check the length of the String and then compare them. In java 8 is done like this:
It first compare each element by length then apply check by compareTo as the input the same as the element to compare with.
If you prefer to use a more understandable method, the above code will be equivalent with below code:
Because the TreeMap constructor accepts the comparator Interface you can build up any even more complex implementation of Composite classes.
This is also another form more simplified version.
How to sort a HashMap in Java [duplicate]
17 Answers 17
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Do you have to use a HashMap? If you only need the Map Interface use a TreeMap
If you want to sort by comparing values in the HashMap. You have to write code to do this, if you want to do it once you can sort the values of your HashMap:
If you want to access this sorted list often, then you could insert your elements into a HashMap , though the semantics of sets and lists are a bit different. Sorted List by hasmap keys: Sorted List by hashmap values: In case of duplicated map values: In any case, you can’t have sorted values in HashMap (according to API This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time ]. Seems like you might want a treemap. You can pass in a custom comparator to it if that applies. Custom compare function which includes functionality for the Turkish alphabet or other different languages than english. here is the using example as the following I need to sort my HashMap according to the values stored in it. The HashMap contains the contacts name stored in phone. Also I need that the keys get automatically sorted as soon as I sort the values, or you can say the keys and values are bound together thus any changes in values should get reflected in keys. Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers. It falls back to sorting by highest score if no posts are trending. Switch to Trending sort A generic version of a method to sort a Map resembles: The following code offers ascending and descending sorting by value: Using newer Java features: Assuming Java, you could sort hashmap just like this: Just a kick-off example. This way is more useful as it sorts the HashMap and keeps the duplicate values as well. You don’t, basically. A HashMap is fundamentally unordered. Any patterns you might see in the ordering should not be relied on. Can you give more context for what you’re trying to do? If you’re really only storing numbers (as strings) for the keys, perhaps a SortedSet such as TreeSet would work for you? Alternatively, you could store two separate collections encapsulated in a single class to update both at the same time?Sorting HashMap by values [duplicate]
12 Answers 12
Trending sort