標籤:compare list 沒有 span str 例子 com hash val
思路:HashMap或Map本身沒有排序功能,若要進行較輕鬆的排序,可利用ArrayList中的sort方法
例子:
import java.util.ArrayList;import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.Map;public class MapSorter { public static void main(String[] args){ Map<String, Integer> map = new HashMap<String, Integer>(); List<Map.Entry<String, Integer>> list = new ArrayList<>(); map.put("Five", 5); map.put("Seven", 7); map.put("Eight", 8); map.put("One",1); map.put("Two",2); map.put("Three", 3); for(Map.Entry<String, Integer> entry : map.entrySet()){ list.add(entry); //將map中的元素放入list中 } list.sort(new Comparator<Map.Entry<String, Integer>>(){ @Override public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return o2.getValue()-o1.getValue();} //逆序(從大到小)排列,正序為“return o1.getValue()-o2.getValue” }); for(Map.Entry<String, Integer> entry: list){ System.out.println(entry); } }}/** 輸出結果:* Eight=8* Seven=7* Five=5* Three=3* Two=2* One=1*/
java根據HashMap中的值將其元素排序