如果我理解正確的話,你想檢索詞的最高計數的列表。這是一些代碼。希望這將有助於:
/**
* This is only convenient facade, using in tests.
*
* @param wordMap
* @param level
* @return
*/
public List<String> getMaxList(Map<String, Integer> wordMap, int level) {
return getMaxList(wordMap.entrySet(), level);
}
/**
* Returns list of words with highest counts, from highest to lowest
*
* @param wordMapEntrySet
* @param level indicates how many words with highest count you want.
* @return
*/
private List<String> getMaxList(Set<Map.Entry<String, Integer>> wordMapEntrySet, int level) {
//Convert set to list, because set is not sortable
List<Map.Entry<String, Integer>> list = new ArrayList<>(wordMapEntrySet);
//Sort the list
list.sort((mapEntry1, mapEntry2) -> {
//Comparing two entries - comparing values (which is actualy a word count)
//Ordering from highest value to lowest
//Changing compare to mapEntry1...compareTo(mapEntry2) will sort the list in reverse order, i.e. from lowest to highest
return mapEntry2.getValue().compareTo(mapEntry1.getValue());
});
//Return a sublist of the sorted list
//Need to return only the keys from the Map.Entry, because the word is the key.
return list.subList(0, level).stream().map(stringIntegerEntry -> stringIntegerEntry.getKey()).collect(Collectors.toList());
}
下面是測試單元測試:
public class WordCountTest {
WordCount wc = new WordCount();
private Map<String, Integer> createMap() {
Map<String, Integer> wordMap = new HashMap<>();
wordMap.put("AA", 3);
wordMap.put("AB", 30);
wordMap.put("AC", 300);
wordMap.put("AD", 3000);
wordMap.put("AE", 30000);
wordMap.put("AF", 1000);
wordMap.put("AG", 100);
wordMap.put("AH", 10);
wordMap.put("AI", 1);
return wordMap;
}
private Map<String, Integer> createMapSame() {
Map<String, Integer> wordMap = new HashMap<>();
wordMap.put("AA", 3);
wordMap.put("AB", 30);
wordMap.put("AC", 300);
wordMap.put("AD", 3000);
wordMap.put("AE", 30000);
wordMap.put("AF", 30000);
wordMap.put("AG", 3000);
wordMap.put("AH", 300);
wordMap.put("AI", 30);
return wordMap;
}
@Test
public void testMaxWordCount() {
List<String> maxWordList = wc.getMaxList(createMap(),3);
Assert.assertEquals(maxWordList.get(0), "AE");
Assert.assertEquals(maxWordList.get(1), "AD");
Assert.assertEquals(maxWordList.get(2), "AF");
}
@Test
public void testMaxWordCountWithSameCount() {
List<String> maxWordList = wc.getMaxList(createMapSame(), 4);
Assert.assertEquals(maxWordList.get(0), "AE");
Assert.assertEquals(maxWordList.get(1), "AF");
Assert.assertEquals(maxWordList.get(2), "AD");
Assert.assertEquals(maxWordList.get(3), "AG");
}
}
我不明白你正在嘗試做的,閱讀代碼是沒有幫助。 –