Map在java8中排序

##HashMap不是有序的 java1.8從新修改了HashMap,結構變爲數組+鏈表+紅黑樹(鏈表>8).所以,順序取決於hash。html

@Test
public void testHashMapShouldBeOrderedButNotAlpha(){
    Map<String, Integer> unsortMap = new HashMap<>();
    unsortMap.put("z", 10);
    unsortMap.put("a", 6);
    unsortMap.put("d", 1);
    unsortMap.put("e", 7);
    unsortMap.put("b", 5);
    unsortMap.put("f", 8);
    unsortMap.put("n", 99);
    unsortMap.put("j", 50);
    unsortMap.put("c", 20);
    unsortMap.put("m", 2);
    unsortMap.put("f", 9);

    Assert.assertEquals("{a=6, b=5, c=20, d=1, e=7, f=9, z=10, j=50, m=2, n=99}",
            unsortMap.toString());
}

##使用stream排序收集爲LinkedHashMap 所以,若是想要有序的map則必須轉換成LinkedHashMapjava

@Test
public void testHashMapSortByValueDesc(){
    Map<String, Integer> 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("j", 50);
    unsortMap.put("m", 2);
    unsortMap.put("f", 9);

    LinkedHashMap<String, Integer> orderMap = unsortMap.entrySet().stream()
            .sorted(Map.Entry.comparingByValue(Collections.reverseOrder()))
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (e1, e2) -> e1,
                    LinkedHashMap::new
            ));
    Assert.assertEquals("{n=99, j=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}",
            orderMap.toString());
    }

###參考數組

相關文章
相關標籤/搜索