我有我的方法應該回傳帶有地圖值的字串。但問題是下面代碼的輸出是
一些單詞示例
代替
一些 - 2,單詞 - 6,示例 - 4
public static void main(String[] args) {
Map<String, Integer> myMap = new HashMap<>();
myMap.put("Some", 2);
myMap.put("Example", 4);
myMap.put("Word", 6);
System.out.println(countWords(myMap));
}
public static String countWords(Map<String, Integer> stringIntegerHashMap) {
String result = stringIntegerHashMap.entrySet().stream()
.map(e -> e.getKey())
.collect(Collectors.joining("\r\n"));
return result;
}
uj5u.com熱心網友回復:
Collectors.joining(...)只負責Stream用分隔符連接-elements。在給定的情況下,然而,我們必須先上圖Stream-emements,即Map.EntryS,在“正確的格式”,即"<key> - <value>"。為此,我們修改了使用的函式Stream::map:
public static String countWords(Map<String, Integer> stringIntegerHashMap) {
return stringIntegerHashMap.entrySet().stream()
.map(entry -> entry.getKey() " - " entry.getValue())
.collect(Collectors.joining("\r\n"));
}
Ideone demo
uj5u.com熱心網友回復:
現在map您只保留鍵,您需要將鍵與值連接起來
public static String countWords(Map<String, Integer> stringIntegerHashMap) {
return stringIntegerHashMap.entrySet().stream()
.map(e -> e.getKey() " - " e.getValue())
.collect(Collectors.joining("\r\n"));
}
Some-2
Word-6
Example-4
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/402530.html
標籤:
