java 7 java 8 map 排序

Java7
1 treeMap

/**
	 * 使用 Map按key进行排序
	 * 
	 * @param map
	 * @return
	 */

	public static Map sortMapByKey(Map map) {
		if (map == null || map.isEmpty()) {
			return null;
		}

		Map sortMap = new TreeMap(new Comparator() {

			@Override
			public int compare(String str1, String str2) {
				// TODO Auto-generated method stub
				return str1.compareTo(str2);
			}
		});

		sortMap.putAll(map);
		return sortMap;
	}
	public static void main(String[] args) {
		Map map = new TreeMap();

        map.put("1", "kfc");
        map.put("2", "wnba");
        map.put("NBA", "nba");
        map.put("CBA", "cba");

        Map resultMap = sortMapByKey(map);    //按Key进行排序

        for (Map.Entry entry : resultMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
	}

//2list排序
//list.sort()或者collections.sort

LinkedList> linkedList = new LinkedList<>(map.entrySet());
//jdk1.8
			linkedList.sort(new Comparator>() {
				@Override
				public int compare(Entry o1, Entry o2) {
					return o1.getKey().compareTo(o2.getKey());
				}
			});
//jdk1.7

Collections.sort(linkedList, new Comparator>(){
				@Override
				public int compare(Entry o1, Entry o2) {
					// TODO Auto-generated method stub
					return o1.getKey().compareTo(o2.getKey());
				}
			});

// Java8

        Map unsortMap = new HashMap<>();
        unsortMap.put("z", 10);
        unsortMap.put("b", 5);
        unsortMap.put("a", 6);
        unsortMap.put("c", 20);
        unsortMap.put("d", 1);
        unsortMap.put("e", 7);
        unsortMap.put("y", 8);
        unsortMap.put("n", 99);
        unsortMap.put("g", 50);
        unsortMap.put("m", 2);
        unsortMap.put("f", 9);
 
        System.out.println("Original...");
        System.out.println(unsortMap);
 
        // sort by keys, a,b,c..., and return a new LinkedHashMap
        // toMap() will returns HashMap by default, we need LinkedHashMap to keep the order.
        Map result = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
 
 
        // Not Recommend, but it works.
        //Alternative way to sort a Map by keys, and put it into the "result" map
        Map result2 = new LinkedHashMap<>();
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
 
        System.out.println("Sorted...");
        System.out.println(result);
        System.out.println(result2);

链接:https://blog.csdn.net/wangmuming/article/details/78448394

你可能感兴趣的:(工具类)