在 Java 中将流转换为字符串 | 您所在的位置:网站首页 › 字典转换为字符串java › 在 Java 中将流转换为字符串 |
这很容易做到,您可以使用 Steams API 来做到这一点。首先,您将映射中的每个条目映射到单个字符串 - 键和值的串联字符串。一旦有了它,您就可以简单地使用reduce()方法或collect()方法来完成它。 使用“reduce()”方法的代码片段将如下所示: Map map = new HashMap(); map.put("sam1", "sam1"); map.put("sam2", "sam2"); String concatString = map.entrySet() .stream() .map(element-> element.getKey().toString() + " : " + element.getValue().toString()) .reduce("", (str1,str2) -> str1 + " , " + str2).substring(3); System.out.println(concatString); 这将为您提供以下输出: sam2 : sam2 , sam1 : sam1 您还可以使用collect()' method instead ofreduce()` 方法。它看起来像这样: String concatString = map.entrySet() .stream() .map(element-> element.getKey().toString() + " : " + element.getValue().toString()) .collect(Collectors.reducing("", (str1,str2) -> str1 + " , " + str2)).substring(3); 两种方法都提供相同的输出。 |
CopyRight 2018-2019 实验室设备网 版权所有 |