我有一個單詞列表,說的Java 8 - 詞的計數,然後在遞減順序排列
List<String> words = Arrays.asList("Hello alan i am here where are you"+
"and what are you doing hello are you there");
我怎樣才能獲得前七名的話,其按降序重複不止一次在列表中?然後單個詞條應按字母順序排列。所以上面的輸出應該是那些前七位字
you (3)
are (2)
hello (2)
alan (1)
am (1)
and (1)
doing (1)
我正在看Java-8使用流,lamda來做這件事。
我想用這種方式。 首先排序列表 二獲得單詞的地圖,其在單詞列表單詞計數。
List<String> sortedWords = Arrays.asList("Hello alan i am here where are you and what are you doing hello you there".split(" "))
.stream().sorted().collect(toList());
Map<String, Long> collect =
sortedWords.stream().collect(groupingBy(Function.identity(), counting()));
這裏我更傾向於將讓這個兩個顯式流管道,而不是做.entrySet()流處理計數,則()在「中間」,因爲它更清楚實際發生了什麼 - 您正在執行兩個不同的流操作。這增強了可讀性,而沒有任何運行成本。 (更一般地說,雖然方法鏈是做飯,但很容易被過度使用 - 只是因爲你可以鏈接,並不意味着你必須一直這樣做。) –
@Brain,我會拿這個,因爲它會更具可讀性如上所述 – bhupen