Skip to content

Commit 87d120c

Browse files
author
rpanjrath
committed
Maps: Map that should be sorted on the basis of values and not keys.
1 parent a4ee3bd commit 87d120c

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,9 @@ Maps
117117
2. Least Recently Used (LRU) cache implementation.
118118
Link: https://github.com/techpanja/interviewproblems/blob/master/src/maps/lrucache/LRUCache.java
119119

120+
3. Map that should be sorted on the basis of values and not keys. (Use of treemap and comparator.)
121+
Link:
122+
120123
Number-Problems
121124
---------------
122125
1. Concatenate two numbers. for e.g. 123, 0456 = 1230456
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)