How to sort map by keys/values in Java

This post will explain you how to sort map by keys/values. I have created one Utility class for the same which you can use to sort map by keys or values.

Utility class to sort Map by keys and values

package com.elitejavacoder.util;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class MapUtility {

    public static <K, V extends Comparable<V>> Map<K, V> sortOnValues(Map<K, V> unsortedMap) {
        Map<K, V> sortedMap = new TreeMap<K, V>(new MapValueComparator<K, V>(unsortedMap));
        sortedMap.putAll(unsortedMap);
        return sortedMap;
    }

    public static <K, V extends Comparable<V>> Map<K, V> sortOnKeys(Map<K, V> unsortedMap) {
        Map<K, V> sortedMap = new TreeMap<K, V>();
        sortedMap.putAll(unsortedMap);
        return sortedMap;
    }

}

class MapValueComparator<K, V extends Comparable<V>> implements Comparator<K> {
    Map<K, V> map;

    MapValueComparator(Map<K, V> map) {
        this.map = map;
    }

	public int compare(K key1, K key2) {
		V value1 = map.get(key1);
		V value2 = map.get(key2);

		return value1.compareTo(value2);
	}
}

Sort Map of java objects by keys and values

Map<String, String> unsortedMap = new HashMap<String, String>();  
unsortedMap.put("1", "Z");
unsortedMap.put("2", "C");
unsortedMap.put("7", "E");
unsortedMap.put("4", "A");
unsortedMap.put("6", "B");
unsortedMap.put("5", "N");
unsortedMap.put("3", "P");

System.out.println("Unsorted Map: " + unsortedMap);

Map<String, String> sortedMapByKeys = MapUtility.sortOnKeys(unsortedMap);
System.out.println("Sorted Map by Keys: " + sortedMapByKeys);

Map<String, String> sortedMapByValues = MapUtility.sortOnValues(unsortedMap);
System.out.println("Sorted Map by Values: " + sortedMapByValues);

Run above sample code which is using map utility to test map sorting on keys and values. You will get following output so we can see that map is sorted as expected.

Unsorted Map: {3=P, 2=C, 1=Z, 7=E, 6=B, 5=N, 4=A}
Sorted Map by Keys: {1=Z, 2=C, 3=P, 4=A, 5=N, 6=B, 7=E}
Sorted Map by Values: {4=A, 6=B, 2=C, 7=E, 5=N, 3=P, 1=Z}

Sort Map of user defined objects by keys and values

To test Map utility against user defined objects I have created Employee class which implements Comparable interface. I have overridden compareTo() method to compare Employee objects on name so Employee objects should be sorted on name. Employee class is as follow:

package com.elitejavacoder.util;

public class Employee implements Comparable&lt;Employee&gt; {
    long id;
    String name;

    Employee(long id, String name) {
        this.id = id;
        this.name = name;
    }
    
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int compareTo(Employee obj) {
        return this.name.compareTo(obj.getName()); // Compare on name
    }
    
    @Override
    public String toString() {
        return this.name;
    }
}

// Sort map of user defined objects
Map<Long, Employee> unsortedMap = new HashMap<Long, Employee>();
unsortedMap.put(new Long(9), new Employee(9, "Ankur"));
unsortedMap.put(new Long(6), new Employee(6, "Sanket"));
unsortedMap.put(new Long(4), new Employee(4, "Devang"));
unsortedMap.put(new Long(7), new Employee(7, "Timir"));
unsortedMap.put(new Long(3), new Employee(3, "Jay"));
unsortedMap.put(new Long(1), new Employee(1, "Atul"));

System.out.println("Unsorted Map: " + unsortedMap);

Map<Long, Employee> sortedMapByKeys = MapUtility.sortOnKeys(unsortedMap);
System.out.println("Sorted Map by Keys: " + sortedMapByKeys);

Map<Long, Employee> sortedMapByValues = MapUtility.sortOnValues(unsortedMap);
System.out.println("Sorted Map by Values: " + sortedMapByValues);

Run above sample code which is using map utility to test map sorting on keys and values. You will get following output so we can see that map is sorted as expected.

Unsorted Map: {1=Atul, 3=Jay, 4=Devang, 6=Sanket, 7=Timir, 9=Ankur}
Sorted Map by Keys: {1=Atul, 3=Jay, 4=Devang, 6=Sanket, 7=Timir, 9=Ankur}
Sorted Map by Values: {9=Ankur, 1=Atul, 4=Devang, 3=Jay, 6=Sanket, 7=Timir}

Apache Ant-Contrib Tutorial 2

In second part of ant-contrib tutorial i will explain some more tasks. First part of this tutorial is available here.

Use switch case in ant.

This task provides similar functionality provided by switch case in Java. You could find more details about this task here.

<target name="test-ant-contrib">
	<switch value="${testValue}" caseinsensitive="true">
		<case value="A">
			<echo message="Test value you have specified is A." />
		</case>
		<case value="B">
			<echo message="Test value you have specified is B." />
		</case>
		<default>
			<echo message="Test value you have specified is other then A/B." />
		</default>
	</switch>
</target>

Use following command to test above example.

ant test-ant-contrib -DtestValue=A

ant test-ant-contrib -DtestValue=a

ant test-ant-contrib -DtestValue=C

Note that at least one <case> or <default> is required. The default case must not appear more than once. In above switch i declared caseinsensitive to true so you will get same output for the first two commands. You can try with caseinsensitive = false.

Perform mathematical operations in ant.

This task provides support for all the basic mathematical operations provided by the java.lang.Math class. It supports int, long, float and double data types. You could find more details about this task here.

<target name="test-ant-contrib">
	<fail message="Please provide testValue1, testValue2, operation and datatype.">
		<condition>
			<or>
				<equals arg1="${testValue1}" arg2=""/>
				<not><isset property="testValue1"/></not>
				<equals arg1="${operation}" arg2=""/>
				<not><isset property="operation"/></not>
				<equals arg1="${testValue2}" arg2=""/>
				<not><isset property="testValue2"/></not>
				<equals arg1="${datatype}" arg2=""/>
				<not><isset property="datatype"/></not>
			</or>
		</condition>
	</fail>
	<math result="result" operand1="${testValue1}" operation="${operation}" operand2="${testValue2}" datatype="${datatype}"/>
	<echo message="Result: ${result}" />
</target>

Run above target using ant test-ant-contrib -DtestValue1=11 -Doperation=+ -DtestValue2=39 -Ddatatype=int to test above example. Try some other mathematical operations with this task.

Replace string in ant

This task allows you to perform regular expression operations on an input string, and sets the results to a property. You can replace string with another string based on matching expression. You could find more details about this task here.

<target name="test-ant-contrib">
	<propertyregex property="newValue" input="${testValue}" regexp="." replace="_" casesensitive="false" />
	<echo message="Result: ${newValue}" />
</target>

Run above target using ant test-ant-contrib -DtestValue=A.B.C.D to test above example. Here in this example i replaced “.” with “_” but you can do lot more using this task.

Sort list values in ant

This task provides functionality to sort a delimited list of items in their natural string order. You could find more details about this task here.

<target name="test-ant-contrib">
	<sortlist property="sortedValues" value="${testValues}" delimiter="," casesensitive="false"/>
	<echo message="Sorted Values: ${sortedValues}" />
</target>

Run above target using ant test-ant-contrib -DtestValues=”z,y,x,w,P,b,c” to test above example. Here i defined casesensitive = false, try above example using casesensitive = true.

Mutable Variable or property in ant

This task provides a mutable property to Ant and works much like variable assignment in Java. This task is similar to the standard Ant Property task, except that THESE PROPERTIES ARE MUTABLE. You could find more details about this task here.

<target name="test-ant-contrib">
	<var name="var1" value="20"/>
	<echo message="Initial value: ${var1}" />
	<var name="var1" value="30"/>
	<echo message="New value: ${var1}" />
</target>

Run above target using ant test-ant-contrib to test above example.