在 Java 中将流转换为字符串

我想将 Map<> 的 Stream 转换为 String,并将其附加到 textArea。我尝试了一些方法,最后一个是使用 StringBuilder,但它们不起作用。


public <K, V extends Comparable<? super V>> String sortByAscendentValue(Map<K, V> map, int maxSize) {


    StringBuilder sBuilder = new StringBuilder();


    Stream<Map.Entry<K,V>> sorted =

            map.entrySet().stream()

               .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()));


    BufferedReader br = new BufferedReader(new InputStreamReader((InputStream) sorted));

    String read;


    try {

        while ((read=br.readLine()) != null) {

            //System.out.println(read);

            sBuilder.append(read);

        }

    } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }


    sorted.limit(maxSize).forEach(System.out::println);


    return sBuilder.toString();

}


慕斯709654
浏览 160回答 3
3回答

慕娘9325324

您可以按如下方式将条目收集到一个条目中String:&nbsp;&nbsp;String&nbsp;sorted&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;map.entrySet().stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.map(e->&nbsp;e.getKey().toString()&nbsp;+&nbsp;"="&nbsp;+&nbsp;e.getValue().toString()) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.joining&nbsp;(","));

慕斯王

考虑对@Eran的代码进行细微更改,因为它已经为您HashMap.Entry.toString()加入了:=String&nbsp;sorted&nbsp;= &nbsp;&nbsp;&nbsp;&nbsp;map.entrySet().stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.sorted(Collections.reverseOrder(Map.Entry.comparingByValue())) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.map(Objects::toString) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.joining(","));

慕后森

这很容易做到,您可以使用 Steams API 来做到这一点。首先,您将映射中的每个条目映射到单个字符串 - 键和值的串联字符串。一旦有了它,您就可以简单地使用reduce()方法或collect()方法来完成它。使用“reduce()”方法的代码片段将如下所示:&nbsp; &nbsp; Map<String, String> map = new HashMap<>();&nbsp; &nbsp; map.put("sam1", "sam1");&nbsp; &nbsp; map.put("sam2", "sam2");&nbsp; &nbsp; String concatString = map.entrySet()&nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; .map(element-> element.getKey().toString() + " : " + element.getValue().toString())&nbsp; &nbsp; &nbsp; &nbsp; .reduce("", (str1,str2) -> str1 + " , " + str2).substring(3);&nbsp; &nbsp; System.out.println(concatString);这将为您提供以下输出:sam2 : sam2 , sam1 : sam1您还可以使用collect()' method instead ofreduce()` 方法。它看起来像这样:&nbsp; &nbsp; String concatString = map.entrySet()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(element-> element.getKey().toString() + " : " + element.getValue().toString())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.reducing("", (str1,str2) -> str1 + " , " + str2)).substring(3);两种方法都提供相同的输出。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java