Sort map by value in ascending order
Here given code implementation process.
/*
Java program
Sort map by value in ascending order
*/
import java.util.*;
public class SortElement
{
// Display map element
public void showMap(Map <Integer,Integer> mp)
{
// iterate map elements
for (int key: mp.keySet())
{
System.out.print("\n "+key + " : " + mp.get(key));
}
}
// This function which is sort the map element by value
public <K, V extends Comparable<? super V>> Map<K, V> sortMapByValue(Map<K, V> map)
{
List< Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
list.sort( Map.Entry.comparingByValue());
// Auxiliary map which is sort given map element
Map<K, V> auxiliary = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list)
{
// Add new key and value
auxiliary.put(entry.getKey(), entry.getValue());
}
return auxiliary;
}
public static void main(String[] args)
{
SortElement task = new SortElement();
// Define map
Map <Integer,Integer> mp = new HashMap <> ();
// Add map elements
mp.put(1,7);
mp.put(2,7);
mp.put(3,3);
mp.put(4,-2);
mp.put(5,1);
mp.put(11,9);
System.out.print(" Before Sort : ");
// Show map element
task.showMap(mp);
mp = task.sortMapByValue(mp);
System.out.print("\n After Sort : ");
// Show map elem
task.showMap(mp);
}
}
Output
Before Sort :
1 : 7
2 : 7
3 : 3
4 : -2
5 : 1
11 : 9
After Sort :
4 : -2
5 : 1
3 : 3
1 : 7
2 : 7
11 : 9
// Include header file
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
/*
C++ program
Sort map by value in ascending order
*/
bool compare(pair < int, int > &i, pair < int, int > &j)
{
return (i.second < j.second);
}
// This function which is sort the map element by value
void sortMapByValue(map < int, int > &mp)
{
cout << " Before Sort : ";
for (auto &it: mp)
{
cout << "\n " << it.first << " : " << it.second;
}
// Use vector to sort map element
vector < pair < int, int >> auxiliary;
// Add map elements into vector
for (auto &it: mp)
{
auxiliary.push_back(it);
}
// Sort using comparator function
sort(auxiliary.begin(), auxiliary.end(), compare);
cout << "\n After Sort : ";
for (auto &it: auxiliary)
{
cout << "\n " << it.first << " : " << it.second;
}
}
int main()
{
// Define map
map < int, int > mp;
mp[1] = 7;
mp[2] = 7;
mp[3] = 3;
mp[4] = -2;
mp[5] = 1;
mp[11] = 9;
sortMapByValue(mp);
return 0;
}
Output
Before Sort :
1 : 7
2 : 7
3 : 3
4 : -2
5 : 1
11 : 9
After Sort :
4 : -2
5 : 1
3 : 3
1 : 7
2 : 7
11 : 9
// Include namespace system
using System;
using System.Linq;
using System.Collections.Generic;
/*
C# program
Sort dictionary by value in ascending order
*/
public class SortElement
{
public static void Main(String[] args)
{
// Define map
Dictionary < int, int > dict = new Dictionary <int, int> ();
dict.Add(1, 7);
dict.Add(2, 7);
dict.Add(3, 3);
dict.Add(4, -2);
dict.Add(5, 1);
dict.Add(11, 9);
Console.Write(" Before Sort Dictionary by value : \n");
// Display calculated result
foreach(KeyValuePair < int, int > entry in dict)
{
Console.WriteLine(" " + entry.Key + " : " + entry.Value);
}
// Show map element
Console.Write(" Sorted Dictionary by value : \n");
// Display calculated result
foreach(KeyValuePair < int, int > entry in dict.OrderBy(key => key.Value))
{
Console.WriteLine(" " + entry.Key + " : " + entry.Value);
}
}
}
Output
Before Sort Dictionary by value :
1 : 7
2 : 7
3 : 3
4 : -2
5 : 1
11 : 9
Sorted Dictionary by value :
4 : -2
5 : 1
3 : 3
1 : 7
2 : 7
11 : 9
class SortElement
{
// Display map element
showMap(mp)
{
//Display result
for (let [key, value] of mp.entries())
{
console.log(" "+ key + " : " + value);
}
}
}
function main()
{
var task = new SortElement();
// Define map
var mp = new Map();
mp.set(1, 7);
mp.set(2, 7);
mp.set(3, 3);
mp.set(4, -2);
mp.set(5, 1);
mp.set(11, 9);
process.stdout.write(" Before Sort : \n");
// Show map element
task.showMap(mp);
mp = new Map([...mp.entries()].sort((a, b) => a[1] > b[1]));
process.stdout.write("\n After Sort : \n");
// Show map elem
task.showMap(mp);
}
main();
Output
Before Sort :
1 : 7
2 : 7
3 : 3
4 : -2
5 : 1
11 : 9
After Sort :
4 : -2
5 : 1
3 : 3
1 : 7
2 : 7
11 : 9
# Sort dict by value in ascending order
def main() :
# Define dict
dict_item = dict()
dict_item[1] = 7
dict_item[2] = 7
dict_item[3] = 3
dict_item[4] = -2
dict_item[5] = 1
dict_item[11] = 9
print(" Before Sort : ", end = "")
print(dict_item)
result = sorted(dict_item.items(), key = lambda v:(v[1], v[0]))
print("\n Sorted : ", end = "")
print(result)
if __name__ == "__main__": main()
Output
Before Sort : {1: 7, 2: 7, 3: 3, 4: -2, 5: 1, 11: 9}
Sorted : [(4, -2), (5, 1), (3, 3), (1, 7), (2, 7), (11, 9)]
class SortElement
# Display Hash element
def showMap(mp)
mp.each{ |key,value| puts " #{key} : #{value}" }
end
end
def main()
task = SortElement.new()
# Define Hash
mp = Hash.new
mp[1] = 7
mp[2] = 7
mp[3] = 3
mp[4] = -2
mp[5] = 1
mp[11] = 9
print(" Before Sort : \n")
# Show map element
task.showMap(mp)
mp = mp.sort_by {|_key, value| value}
print("\n After Sort : \n")
# Show map elem
task.showMap(mp)
end
main()
Output
Before Sort :
1 : 7
2 : 7
3 : 3
4 : -2
5 : 1
11 : 9
After Sort :
4 : -2
5 : 1
3 : 3
1 : 7
2 : 7
11 : 9
import scala.collection.immutable.ListMap;
/*
Scala program
Sort map by value in ascending order
*/
class SortElement
{
// Display map element
def showMap( mp : Map[Int, Int] ): Unit = {
mp.keys.foreach
{
key => println(" " + key + " : " + mp(key));
}
}
}
object Main
{
def main(args: Array[String]): Unit = {
var task: SortElement = new SortElement();
// Define map
var mp : Map[Int, Int] = Map();
mp += (1->(7));
mp += (2->(7));
mp += (3->(3));
mp += (4->(-2));
mp += (5->(1));
mp += (11->(9));
print(" Before Sort : \n");
// Show map element
task.showMap(mp);
val result = ListMap(mp.toSeq.sortBy(_._2):_*)
print("\n After Sort : \n");
// Show map elem
task.showMap(result);
}
}
Output
Before Sort :
5 : 1
1 : 7
2 : 7
3 : 3
11 : 9
4 : -2
After Sort :
4 : -2
5 : 1
3 : 3
1 : 7
2 : 7
11 : 9
/*
Swift 4 program
Sort map by value in ascending order
*/
func main()
{
// Define dictionary
var dictItem = [Int: Int]();
dictItem[1] = 7;
dictItem[2] = 7;
dictItem[3] = 3;
dictItem[4] = -2;
dictItem[5] = 1;
dictItem[11] = 9;
print(" Before Sort : ");
for (key,value) in dictItem
{
print("\(key) : \(value)")
}
let result = dictItem.sorted { $0.1 < $1.1 };
print("\n After Sort : ");
// Show dict element
for (key,value) in result
{
print("\(key) : \(value)")
}
}
main();
Output
Before Sort :
5 : 1
11 : 9
2 : 7
3 : 3
1 : 7
4 : -2
After Sort :
4 : -2
5 : 1
3 : 3
2 : 7
1 : 7
11 : 9
/*
Kotlin program
Sort map by value in ascending order
*/
class SortElement
{
// Display map element
fun showMap(mp: HashMap < Int, Int > ): Unit
{
for (key in mp.keys)
{
println(" " + key + " : " + mp[key]);
}
}
}
fun main(args: Array < String > ): Unit
{
var task: SortElement = SortElement();
// Define map
var mp = hashMapOf < Int , Int > ();
mp.put(1, 7);
mp.put(2, 7);
mp.put(3, 3);
mp.put(4, -2);
mp.put(5, 1);
mp.put(11, 9);
print(" Before Sort : \n");
// Show map element
task.showMap(mp);
var result = mp.toList().sortedBy { (_, value) -> value}.toMap()
print("\n After Sort : \n");
for (key in result.keys)
{
println(" " + key + " : " + mp[key]);
}
}
Output
Before Sort :
1 : 7
2 : 7
3 : 3
4 : -2
5 : 1
11 : 9
After Sort :
4 : -2
5 : 1
3 : 3
1 : 7
2 : 7
11 : 9
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment