2017-09-16 51 views
1

我有一個HashMap,我需要按值排序,我試圖保持簡潔,所以我使用Java 8.但是各種方法不工作,我我不確定爲什麼。我已經試過這樣:在Java中按值排序Hashmap 8

followLikeCount.values() 
    .stream() 
    .sorted(Map.Entry.comparingByValue()) 
    .collect(Collectors.toList()); 

會拋出這個編譯時異常:

Main.java:65: error: no suitable method found for sorted(Comparator<Entry<Object,V#1>>) 
    .sorted(Map.Entry.comparingByValue()) 

我不明白爲什麼有從觀察的不匹配。我也嘗試過使用比較器:

Comparator<Map.Entry<Integer, Integer>> byValue = 
      Map.Entry.<Integer, Integer>comparingByValue(); 

這會產生類似的錯誤。請你能提醒比較者爲什麼無效?

+0

是否'值()'以鍵/值對,或者只值返回'Entry'? – markspace

+0

啊,真的,只是值,但我不能把HashMap followLikeCount直接轉換成流。完全需要一種不同的方法嗎? – Bryn

+1

嘗試'entrySet()'。你可以流式傳輸。 – markspace

回答

5

您嘗試通過values()

followLikeCount.values() 
    .stream() 
    .sorted(Map.Entry.comparingByValue()) 
    .collect(Collectors.toList()); 

使用上List<Integer>一個Comparator<Map.Entry<Integer, Integer>>返回你需要使用一個Set<Map.Entry<Integer, Integer>>這個比較可以通過entrySet()返回:

List<Map.Entry<Integer, Integer>> list = followLikeCount.entrySet() 
                .stream() 
                .sorted(Map.Entry.comparingByValue()) 
                .collect(Collectors.toList()); 

如果你只想得到值,排序,你可以改變Comparator並取回一個List<Integer>

List<Integer> list = followLikeCount.values() 
      .stream() 
      .sorted(Comparator.naturalOrder()) 
      .collect(Collectors.toList()); 
+0

如果你只想得到排序的(Comparable)值,你甚至可以使用比較器'followLikeCount.values().stream().sorted().collect(Collectors.toList());'。或者沒有流:'List list = new ArrayList <>(followLikeCount.values()); list.sort(NULL);' – Holger