根据map的value进行排序2

JAVA对Map按Value值排序

在java实际编程中经常需要使用到HashMap,TreeMap以及LinkedHashMap来保存键值对,而java中对Map按Value排序并没有已经写好的方法,需要自己实现。
作者使用了自定义类以及Collections包的sort()方法实现Map的按值排序,具体代码如下:

  1. sortMap()
    输入参数为需要排序的Map,输出为LinkedHashMap类型,因为需要保证顺序。
	public static LinkedHashMap<String, Integer> sortMap(Map<String, Integer> map){
		class MapClass{															//自定义类保存键值对
			private String key;
			private int value;
			
			public MapClass(String key, int value) {
				super();
				this.key = key;
				this.value = value;
			}

			public String getKey() {
				return key;
			}

			public int getValue() {
				return value;
			}
			
			
		}
		class MapSortMethod implements Comparator<MapClass>{					//为自定义类实现排序方法
			@Override
			public int compare(MapClass o1, MapClass o2) {
				int result = Integer.compare(o1.getValue(), o2.getValue());		//按值大小升序排列
				//int result = Integer.compare(o2.getValue(), o1.getValue());	//按值大小降序排列	
				if(result != 0)
					return result;		
				return o1.getKey().compareTo(o2.getKey());						//值相同时按键字典顺序排列
			}
		}
		
		ArrayList<MapClass> mapclass = new ArrayList<MapClass>();				//以ArrayList保存自定义类
		for(String k: map.keySet())
			mapclass.add(new MapClass(k, map.get(k)));
		Collections.sort(mapclass, new MapSortMethod());						//使用Collections.sort()方法,第二个参数为自定义排序方法,需要实现Comparator接口
						
		LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
		for(MapClass m: mapclass)
			sortedMap.put(m.getKey(), m.getValue());
		return sortedMap;														//用LinkedHashMap返回排好序的Map
	}
  1. 测试
	public static void main(String[] args) {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		map.put("math", 93);
		map.put("english", 88);
		map.put("chinese", 99);
		map.put("biology", 72);
		System.out.println(sortMap(map));
	}

输出结果如下:
在这里插入图片描述
注: 本文中使用到的依赖包如下:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

猜你喜欢

转载自blog.csdn.net/Romantic_321/article/details/112664403