Java

Sort HashMap and TreeMap by keys and values in java 8 using netbeans

Description:

Sorting data is often used when dealing with Java Maps. This time, I will explain how to sort HashMap in java.

This article is about sorting HashMap in java using NetBeans ide

  • HashMap sorting method in java
  • How to sort TreeMap in java
  • How to sort by multiple keys in java




HashMap sorting method in java

Here, about HashMap sorting,

  • How to sort by key name
  • How to sort in ascending and descending order by specifying a value

Each method will be explained.

How to sort Map by key name in java

When sorting a Map by key name, use the Object class to get the number of elements in the Map and use the Arrays.sort method to sort. The method for sorting by key name is described below.

Note that java.util.Arrays must be imported to use the Arrays.sort method.

package com.mycompany.javabasics;

import java.util.Map;

import java.util.HashMap;

import java.util.Arrays;

/**

*

* @author Fawadkhan

*/

public class MapExamples {

public static void main(String[] args) {

// map declaration

Map<Integer, String>myData = new HashMap<Integer, String>();

// Store data in Map

myData.put(1, “A”);

myData.put(7, “G”);

myData.put(3, “C”);

myData.put(6, “F”);

myData.put(5, “E”);

myData.put(4, “D”);

myData.put(2, “B”);

// sort map by key

Object[] Datakey = myData.keySet().toArray();

Arrays.sort(Datakey);

for (Integer SortKey : myData.keySet()) {

System.out.println(myData.get(SortKey));

}

}

}

Output:

sorting map in java

In the above code, values ​​are set in the order of key names 1, 7, 3, 6,5,4, and 2 in the defined Map variable mydata. Declare an Object class and get all Map elements in the variable Datakey. Next, the sort method of the Arrays class is used to sort the keys of the Map. As you can see  in the output image the data is sorted



How to sort Map by value (in ascending and descending order)

Here, specify the values ​​of the Map and describe how to sort hashmap in ascending and descending order.

package com.mycompany.javabasics;

import java.util.ArrayList;

import java.util.Map;

import java.util.HashMap;

import java.util.Arrays;

import java.util.Collections;

import java.util.Comparator;

importjava.util.List;

import java.util.Map.Entry;

/**

*

* @author Fawadkhan

*/

public class MapExamples {

public static void main(String[] args) {

Map<String, Integer>MapData = new HashMap<String, Integer>();

//step1. Store data in Map

MapData.put(“A”, 1);

MapData.put(“G”, 7);

MapData.put(“B”, 2);

MapData.put(“D”, 4);

MapData.put(“C”, 3);

MapData.put(“F”, 6);

MapData.put(“E”, 5);

// step2. Create a list of Map.Entry

List<Entry<String, Integer>>list_entries = new ArrayList<Entry<String, Integer>>(MapData.entrySet());

// step3. Compare Map.Entry values using the comparison function Comparator (ascending order)

Collections.sort(list_entries, new Comparator<Entry<String, Integer>>() {

publicint compare(Entry<String, Integer> obj1, Entry<String, Integer> obj2) {

// step4. ascending order

return obj1.getValue().compareTo(obj2.getValue());

}

});

System.out.println(“Map Sorted in ascending order”);

// step5. Get values in order of elements in a loop

for (Entry<String, Integer> entry : list_entries) {

System.out.println(entry.getKey() + ” : ” + entry.getValue());

}

// step6. Compare the Map.Entry values using the comparison function Comparator (descending order)

Collections.sort(list_entries, new Comparator<Entry<String, Integer>>() {

//Use //compare to compare values

publicint compare(Entry<String, Integer> obj1, Entry<String, Integer> obj2)

{

//descending order

return obj2.getValue().compareTo(obj1.getValue());

}

});

System .out .println ( “Map Sorted in descending order” );

//step 7. Get values in order of elements in a loop

for(Entry<String, Integer> entry : list_entries) {

System.out.println(entry.getKey() + ” : ” + entry.getValue());

}

}

}

Output:

sorting map in java

The details of 1 to 7 step described in the comments in the above code are explained below.

  1. Set values ​​in the order of key names 1, 7, 2, 4,3,6, and 5 in the defined Map variable MapData
  2. Create a list of Map Entries (key-value pairs)
  3. Use the sort method of the Collection class, compare the values ​​of the Map Entry with the comparison function Comparator, and define obj1 (ascending order) and obj2 (descending order) of the Map Entry using the compare function.
  4. Return elements sorted in descending order using compare To method
  5. If you display the number of elements in the order in a loop, they will be sorted in ascending order.
  6. When sorting in descending order, specify obj2 (descending order) of Entry when using the compare To method and return it OK
  7. If you display the number of elements in the order in a loop, it will be sorted in descending order.



How to sort TreeMap in java:

TreeMap is also a collection class that implements Map like HashMap. The basic usage is the same as HashMap, but as a characteristic of TreeMap, the values ​​stored by the put method are automatically sorted internally and retained. Below is a sample code using TreeMap?

In addition, when using TreeMap in java, it is necessary to import java.util.TreeMap.

package com.mycompany.javabasics;

import java.util.Map;

import java.util.TreeMap;

/**

*

* @author Fawadkhan

*/

public class MapExamples {

public static void main(String[] args) {

Map<Integer, String>MapData = new TreeMap<Integer, String>();

MapData.put(1, “A”);

MapData.put(7, “G”);

MapData.put(2, “B”);

MapData.put(4, “D”);

MapData.put(3, “C”);

MapData.put(6, “F”);

MapData.put(5, “E”);

// Loop for the number of elements of Map using keySet

for (Integer nKey : MapData.keySet()) {

System.out.println(MapData.get(nKey));

}

}

}

Output:

sorting map in java

In the above code, the keys are stored in order s1, 7, 2, 4,3,6, and 5 but if you check the resulting values, you can see in the above image that the value keys are sorted.



How to sort by multiple keys in java

how to sort when Map and List are nested by multiple keys:

Here, I will introduce how to sort when Map and List are nested.

package com.mycompany.javabasics;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

import java.util.TreeMap;

/**

*

* @author Fawadkhan

*/

public class MapExamples {

public static void main(String[] args) {

// Declaration of Map

Map<List, Integer> MapData1 = new HashMap<List, Integer>();

// declaration of list(ListData1)

List<String> ListData1 = new ArrayList<String>();

ListData1.add(“Java”);

MapData1.put(ListData1, 2);

// declaration of list(ListData2)

List<String> ListData2 = new ArrayList<String>();

ListData2.add(“C++”);

MapData1.put(ListData2, 3);

// declaration of list(ListData3)

List<String> ListData3 = new ArrayList<String>();

ListData3.add(“Android”);

MapData1.put(ListData3, 1);

// declaration of list(ListData4)

List<String> ListData4 = new ArrayList<String>();

ListData4.add(“PHP”);

MapData1.put(ListData4, 5);

// declaration of list(ListData5)

List<String> ListData5 = new ArrayList<String>();

ListData5.add(“C#”);

MapData1.put(ListData5, 4);

// create a list of Map.Entry

List<Entry<List, Integer>>list_entries = new ArrayList<Entry<List, Integer>>(MapData1.entrySet());

// Compare Map.Entry values using the comparison function Comparator

Collections.sort(list_entries, new Comparator<Entry<List, Integer>>() {

// compare values using compare

publicint compare(Entry<List, Integer> obj1, Entry<List, Integer> obj2) {

return obj1.getValue().compareTo(obj2.getValue());

}

});

// display the contents of the list in a loop

for (Entry<List, Integer> entry : list_entries) {

System.out.println(entry.getKey() + ” : ” + entry.getValue());

}

}

}

Output:

sorting map in java

In the above code, the Map variable MapData1 stores the created ListData1, ListData2, ListData2, ListData4, and ListData5 in order of Map values ​​2, 3,1,5, and 4, respectively. Next, similarly to the method of sorting by the value of Map, a list of Entries of Map is created and the results sorted using the comparison function are returned.




summary

Here, i have explained sorting by specifying the key name in Map, sorting by specifying the value, and map sorting in ascending and descending order. There are several patterns for sorting collections such as Maps and Lists.

If you forget how to sort hashMap in java, remember this article!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button