//package sk.hasto.java.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Utility functions for working with Maps.
*
* @author Branislav Hasto
*/
public final class MapUtils {
/**
* Sorts map by values in ascending order.
*
* @param
* map keys type
* @param
* map values type
* @param map
* @return
*/
public static > LinkedHashMap sortMapByValue(
Map map) {
List> sortedEntries = sortEntriesByValue(map.entrySet());
LinkedHashMap sortedMap = new LinkedHashMap(map.size());
for (Entry entry : sortedEntries) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
/**
* Sorts map entries by value in ascending order.
*
* @param
* map keys type
* @param
* map values type
* @param entries
* @return
*/
private static > List> sortEntriesByValue(
Set> entries) {
List> sortedEntries = new ArrayList>(entries);
Collections.sort(sortedEntries, new ValueComparator());
return sortedEntries;
}
/**
* Komparator podla hodnot v polozkach mapy.
*
* @param
* typ hodnot
*/
private static class ValueComparator> implements
Comparator> {
public int compare(Entry, V> entry1, Entry, V> entry2) {
return entry1.getValue().compareTo(entry2.getValue());
}
}
}