Map TreeMap key value pair sort by value Java Android example

Map TreeMap sorted by value Java Android example.

MainClass.java

 
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
 
public class MainClass {
	public static void main(String[] arg) {
 
		// english;germany dictionary
		String[] arrayOfString = { "one;eine", "two;zwei", "three;drei",
				"four;vier" };
 
		Map<String, String> map = new TreeMap<String, String>();
 
		for (String s : arrayOfString) {
			String[] array = s.split(";");
			String sKey = "", sValue = "";
			if (array.length > 1) {
				sKey = array[0];
				sValue = array[1];
				map.put(sKey, sValue);
			}
		}
		for (Entry<String, String> entry: mapSortedByValues(map)) {
		    System.out.println(entry.getKey() + " = " + entry.getValue());
		}
	}
 
	static <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> mapSortedByValues(
			Map<K, V> map) {
		SortedSet<Map.Entry<K, V>> sortedSetOfEntries = new TreeSet<Map.Entry<K, V>>(
				new Comparator<Map.Entry<K, V>>() {
					@Override
					public int compare(Map.Entry<K, V> entry_1, Map.Entry<K, V> entry_2) {
						int res = entry_1.getValue().compareTo(entry_2.getValue());
						return res != 0 ? res : 1; 
						// return entry_1.getValue().compareTo(entry_2.getValue());							
					}
				});
		sortedSetOfEntries.addAll(map.entrySet());
		return sortedSetOfEntries;
	}
}
/*
three = drei
one = eine
four = vier
two = zwei
 */
This entry was posted in Android Examples Code, Array,List,Collections and tagged , , , . Bookmark the permalink.


Comments are closed.

4,152 views