在实际业务开发中,可能会遇到Java Map按值排序的需要。
Java Map按值排序的常见思路是:
1、 将map中的entry放到List中
2、 对List中的entry通过比较器按值排序
3 、将排序后的entry放到linkedhashmap中
Java 8利用Stream
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import static java.util.Map.Entry.comparingByValue;
import static java.util.stream.Collectors.toMap;
public class SortTest {
public static void main(String[] args) throws Exception {
// 创建一个字符串为Key,数字为值的map
Map<String, Integer> budget = new HashMap<>();
budget.put("clothes", 120);
budget.put("grocery", 150);
budget.put("transportation", 100);
budget.put("utility", 130);
budget.put("rent", 1150);
budget.put("miscellneous", 90);
System.out.println("排序前: " + budget);
// 按值排序 升序
Map<String, Integer> sorted = budget
.entrySet()
.stream()
.sorted(comparingByValue())
.collect(
toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
LinkedHashMap::new));
System.out.println("升序按值排序后的map: " + sorted);
// 按值排序降序
sorted = budget
.entrySet()
.stream()
.sorted(Collections.reverseOrder(comparingByValue()))
.collect(
toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
LinkedHashMap::new));
System.out.println("降序按值排序后的map: " + sorted);
}
}
可以封装成工具类
/**
* Map排序工具类
*
* @author liuwangyanghdu@163.com 明明如月
*/
public class MapSortUtil {
private static Comparator<Map.Entry> comparatorByKeyAsc = (Map.Entry o1, Map.Entry o2) -> {
if (o1.getKey() instanceof Comparable) {
return ((Comparable) o1.getKey()).compareTo(o2.getKey());
}
throw new UnsupportedOperationException("键的类型尚未实现Comparable接口");
};
private static Comparator<Map.Entry> comparatorByKeyDesc = (Map.Entry o1, Map.Entry o2) -> {
if (o1.getKey() instanceof Comparable) {
return ((Comparable) o2.getKey()).compareTo(o1.getKey());
}
throw new UnsupportedOperationException("键的类型尚未实现Comparable接口");
};
private static Comparator<Map.Entry> comparatorByValueAsc = (Map.Entry o1, Map.Entry o2) -> {
if (o1.getValue() instanceof Comparable) {
return ((Comparable) o1.getValue()).compareTo(o2.getValue());
}
throw new UnsupportedOperationException("值的类型尚未实现Comparable接口");
};
private static Comparator<Map.Entry> comparatorByValueDesc = (Map.Entry o1, Map.Entry o2) -> {
if (o1.getValue() instanceof Comparable) {
return ((Comparable) o2.getValue()).compareTo(o1.getValue());
}
throw new UnsupportedOperationException("值的类型尚未实现Comparable接口");
};
/**
* 按键升序排列
*/
public static <K, V> Map<K, V> sortByKeyAsc(Map<K, V> originMap) {
if (originMap == null) {
return null;
}
return sort(originMap, comparatorByKeyAsc);
}
/**
* 按键降序排列
*/
public static <K, V> Map<K, V> sortByKeyDesc(Map<K, V> originMap) {
if (originMap == null) {
return null;
}
return sort(originMap, comparatorByKeyDesc);
}
/**
* 按值升序排列
*/
public static <K, V> Map<K, V> sortByValueAsc(Map<K, V> originMap) {
if (originMap == null) {
return null;
}
return sort(originMap, comparatorByValueAsc);
}
/**
* 按值降序排列
*/
public static <K, V> Map<K, V> sortByValueDesc(Map<K, V> originMap) {
if (originMap == null) {
return null;
}
return sort(originMap, comparatorByValueDesc);
}
private static <K, V> Map<K, V> sort(Map<K, V> originMap, Comparator<Map.Entry> comparator) {
return originMap.entrySet()
.stream()
.sorted(comparator)
.collect(
Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
LinkedHashMap::new));
}
}
package com.chujianyun.common.map;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.util.HashMap;
import java.util.Map;
/**
* Map排序工具类
*
* @author liuwangyanghdu@163.com 明明如月
*/
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MapSortUtilTest {
// 创建一个字符串为Key,数字为值的map
Map<String, Integer> budget = new HashMap<>();
@BeforeAll
public void init() {
budget.put("clothes", 120);
budget.put("grocery", 150);
budget.put("transportation", 100);
budget.put("utility", 130);
budget.put("rent", 1150);
budget.put("miscellneous", 90);
System.out.println("排序前: " + budget);
}
@Test
void sortByKeyAsc() {
System.out.println("按键升序" + MapSortUtil.sortByKeyAsc(budget));
}
@Test
void sortByKeyDesc() {
System.out.println("按键降序" + MapSortUtil.sortByKeyDesc(budget));
}
@Test
void sortByValueAsc() {
System.out.println("按值升序" + MapSortUtil.sortByValueAsc(budget));
}
@Test
void sortByValueDesc() {
System.out.println("按值降序" + MapSortUtil.sortByValueDesc(budget));
}
}
Java 7版本
import java.util.*;
import java.lang.*;
public class GFG {
// hashmap按值排序
public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm)
{
// HashMap的entry放到List中
List<Map.Entry<String, Integer> > list =
new LinkedList<Map.Entry<String, Integer> >(hm.entrySet());
// 对List按entry的value排序
Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
// 将排序后的元素放到LinkedHashMap中
HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> aa : list) {
temp.put(aa.getKey(), aa.getValue());
}
return temp;
}
public static void main(String[] args)
{
HashMap<String, Integer> hm = new HashMap<String, Integer>();
// 填充测试数据
hm.put("Math", 98);
hm.put("Data Structure", 85);
hm.put("Database", 91);
hm.put("Java", 95);
hm.put("Operating System", 79);
hm.put("Networking", 80);
Map<String, Integer> hm1 = sortByValue(hm);
// 打印按值排序后的数据
for (Map.Entry<String, Integer> en : hm1.entrySet()) {
System.out.println("Key = " + en.getKey() +
", Value = " + en.getValue());
}
}
}