您的位置:首页 > 产品设计 > UI/UE

Java基础 —— 根据 Key 或是 Value 对 Map 进行排序

2017-11-26 18:43 931 查看
how to sort Map values by key in Java


https://stackoverflow.com/questions/922528/how-to-sort-map-values-by-key-in-java

Sort a Map<Key, Value> by values (Java)


https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java

根据 Key 对 Map 进行排序

package com.practice.map;

import java.util.*;

public class SortedMapByKey {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("abc", 122);
map.put("bsh", 232);
map.put("dsa", 12);
map.put("aac", 192);

System.out.println("未对 Key 进行排序:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("\"" + entry.getKey() + "\"" + " : " + entry.getValue());
}

System.out.println("-----------------------------");

System.out.println("使用 Collections.sort 对 Key 进行排序:");
List<String> sortedKeys = new ArrayList(map.keySet());
Collections.sort(sortedKeys);
for (String key : sortedKeys){
System.out.println("\"" + key + "\"" + " : " + map.get(key));
}

System.out.println("-----------------------------");

System.out.println("使用 TreeMap 对 Key 进行排序:");
Map<String, Integer> treeMap = new TreeMap<>(map);
for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
System.out.println("\"" + entry.getKey() + "\"" + " : " + entry.getValue());
}
}
}


未对 Key 进行排序:
"aac" : 192
"abc" : 122
"dsa" : 12
"bsh" : 232
-----------------------------
使用 Collections.sort 对 Key 进行排序:
"aac" : 192
"abc" : 122
"bsh" : 232
"dsa" : 12
-----------------------------
使用 TreeMap 对 Key 进行排序:
"aac" : 192
"abc" : 122
"bsh" : 232
"dsa" : 12

Process finished with exit code 0


根据 Value 对 Map 进行排序

Here’s a generic-friendly version you’re free to use:

import java.util.*;

public class MapUtil {
public static <K, V extends Comparable<? super V>> Map<K, V>
sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return (o1.getValue()).compareTo( o2.getValue() );
}
});

Map<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
}


And an associated JUnit4 test so you don’t have to take my word for it:

import java.util.*;
import org.junit.*;

public class MapUtilTest {
@Test
public void testSortByValue() {
Random random = new Random(System.currentTimeMillis());
Map<String, Integer> testMap = new HashMap<String, Integer>(1000);
for(int i = 0; i < 1000; ++i) {
testMap.put( "SomeString" + random.nextInt(), random.nextInt());
}

testMap = MapUtil.sortByValue(testMap);
Assert.assertEquals(1000, testMap.size());

Integer previous = null;
for(Map.Entry<String, Integer> entry : testMap.entrySet()) {
Assert.assertNotNull(entry.getValue());
if (previous != null) {
Assert.assertTrue(entry.getValue() >= previous);
}
previous = entry.getValue();
}
}
}


Java 7 Version

public static <K, V extends Comparable<? super V>> Map<K, V>
sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});

Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}


Java 8 Version. This will sort according to the value in ascending order; for descending order, it is just possible to uncomment the call to Collections.reverseOrder().

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
return map.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(/*Collections.reverseOrder()*/))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(e1, e2) -> e1,
LinkedHashMap::new
));
}


There is one more technique to sort HashMap by Values. Here, no Comparator is used. We do sort based on Keys, swap keys and values, sort based on values and again swap to get the finalMap, which is sorted HashMap based on Values.

private static LinkedHashMap<String, String> method1(HashMap<String, String> originalHashMap) {
LinkedHashMap<String, String> sortedHashMapByKeys = new LinkedHashMap<>(); //maintains the order of putting
TreeMap<String, String> originalTreeMap = new TreeMap<>(originalHashMap); //sorts based on keys
for (Map.Entry<String, String> map: originalTreeMap.entrySet()) {
sortedHashMapByKeys.put(map.getKey(), map.getValue());
}

LinkedHashMap<String, String> reversedOfSortedLinkedHashMap = new LinkedHashMap<>();
for (Map.Entry<String, String> map: sortedHashMapByKeys.entrySet()) {
reversedOfSortedLinkedHashMap.put(map.getValue(), map.getKey());
}

LinkedHashMap<String, String> finalMap = new LinkedHashMap<>();
TreeMap<String, String> treeMapOfReversedOfSortedLinkedHashMap = new TreeMap<>(reversedOfSortedLinkedHashMap);
for (Map.Entry<String, String> map: treeMapOfReversedOfSortedLinkedHashMap.entrySet()) {
finalMap.put(map.getKey(), map.getValue()); //sort and swap
}
return finalMap;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: