Map has Key
and Value
pair, Keys are stored in Set
which removes duplicates. HashMap
internally sorts the entry based on Key
, So we will be using LinkedHashMap
because it keeps unique elements without altering the insertion order.
package org.wesome.dsalgo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class SortMap {
public static Map<Integer, Integer> sortMap(Map<Integer, Integer> map) {
Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
List<Map.Entry<Integer, Integer>> arrayList = new ArrayList(entrySet);
Collections.sort(arrayList, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
map.clear();
for (Map.Entry<Integer, Integer> entry : arrayList) {
map.put(entry.getKey(), entry.getValue());
}
return map;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.IntStream;
public class SortMapTest {
@Test
void sortMapTest1() {
Map<Integer, Integer> map = new LinkedHashMap<>();
Map<Integer, Integer> testMap = new LinkedHashMap();
int range = 5;
IntStream.rangeClosed(0, range).forEach(i -> {
map.put(i, range - i);
testMap.put(range - i, i);
});
Assertions.assertTrue(testMap.equals(SortMap.sortMap(map)));
}
}
plugins {
id 'java'
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}