|
| 1 | +package maps.sortofvaluesinmap; |
| 2 | + |
| 3 | +import java.util.Comparator; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | +import java.util.TreeMap; |
| 7 | + |
| 8 | +/** |
| 9 | + * A map that should be sorted on the basis of values and not keys. |
| 10 | + * Created by techpanja |
| 11 | + * Created on 2/5/14 2:33 PM. |
| 12 | + */ |
| 13 | +public class SortOnValuesInMap { |
| 14 | + |
| 15 | + private SortOnValuesInMap() { |
| 16 | + |
| 17 | + } |
| 18 | + |
| 19 | + public static Map<String, Integer> sortOnValuesInMap(Map<String, Integer> inputMap) { |
| 20 | + ValueComparator valueComparator = new ValueComparator(inputMap); |
| 21 | + Map<String, Integer> sortedMapOnValue = new TreeMap<>(valueComparator); |
| 22 | + sortedMapOnValue.putAll(inputMap); |
| 23 | + return sortedMapOnValue; |
| 24 | + } |
| 25 | + |
| 26 | + static class ValueComparator implements Comparator<String> { |
| 27 | + |
| 28 | + private Map<String, Integer> inputMap; |
| 29 | + |
| 30 | + public ValueComparator(Map<String, Integer> inputMap) { |
| 31 | + this.inputMap = inputMap; |
| 32 | + } |
| 33 | + |
| 34 | + @Override |
| 35 | + public int compare(String string1, String string2) { |
| 36 | + if (inputMap.get(string1) > inputMap.get(string2)) { |
| 37 | + return -1; |
| 38 | + } else { |
| 39 | + return 1; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + public static void main(String[] args) { |
| 45 | + Map<String, Integer> map = new HashMap<>(); |
| 46 | + map.put("A", 2); |
| 47 | + map.put("B", 1); |
| 48 | + map.put("C", 3); |
| 49 | + map.put("D", 0); |
| 50 | + map.put("E", 8); |
| 51 | + Map<String, Integer> output = sortOnValuesInMap(map); |
| 52 | + for (String temp : output.keySet()) { |
| 53 | + System.out.println(temp); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments