![](/img/trans.png)
[英]Request body change when I Use servletRequest.getReader().lines().collect(Collectors.joining())
[英]How can I use .collect(Collectors.joining) to convert Map into String
我的方法應該返回帶有 map 值的字符串。 但問題是下面代碼的output是
一些單詞示例
代替
一些 - 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;
}
現在在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
Collectors.joining(...)
僅負責使用分隔符加入Stream
元素。 然而,在給定的情況下,我們必須首先 map Stream
元素,即Map.Entry
s,在“正確的格式"<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"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.