Coding Gems – Gem #1 – Java Sort Map by Value

package com.wordpress.Oxcafebabe.gems;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 *
 * @author mahdeto
 *
 */
public class SortByValueMaps {

	public static void main(String[] args) {
		Map<String, Integer> test = new HashMap<String, Integer>(3);
		test.put("someValue", 1);
		test.put("aKeyThatNormallyComesBefore", 3);
		test.put("someOtherValue", 2);

		System.out.println(sortMapByValues(test));
	}

	public static <K, V extends Comparable<? super V>> Map<K, V> sortMapByValues(Map<K, V> sortMe) {
		List<Map.Entry<K, V>> entries = new ArrayList<Map.Entry<K, V>>(sortMe.size());

		entries.addAll(sortMe.entrySet());

		Collections.sort(entries, new Comparator<Map.Entry<K, V>>() {

			@Override
			public int compare(Entry<K, V> o1, Entry<K, V> o2) {
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		Map<K, V> sortedMap = new LinkedHashMap<K, V>(sortMe.size());

		for(Map.Entry<K, V> entry : entries) {
			sortedMap.put(entry.getKey(), entry.getValue());
		}

		return sortedMap;
	}

}

This outputs:
{someValue=1, someOtherValue=2, aKeyThatNormallyComesBefore=3}
Advertisement

~ by M@hdeTo on June 14, 2011.

4 Responses to “Coding Gems – Gem #1 – Java Sort Map by Value”

  1. Enta bethazar sa7?
    this is what you did out of boredom?

  2. println(
    Map(“someValue” → 1, “aKeyThatNormallyComesBefore” → 3, “someOtherValue” → 2).toList.sortBy(_._2).toMap) // hehehe

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.