简体   繁体   English

在Java中将Stream转换为String

[英]Convert Stream to String in Java

I want to convert a Stream of a Map<> into a String, to append it to a textArea. 我想将Map <>的Stream转换为String,以将其附加到textArea。 I tried some methods, the last with StringBuilder, but they don't work. 我尝试了一些方法,最后一个使用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();
}

You can collect the entries into a single String as follows: 您可以将条目收集到单个String ,如下所示:

  String sorted =
        map.entrySet().stream()
           .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
           .map(e-> e.getKey().toString() + "=" + e.getValue().toString())
           .collect(Collectors.joining (","));

It is easy to do this, you can use the Steams API to do this. 这很容易做到,你可以使用Steams API来做到这一点。 First, you map each entry in the map to a single string - the concatenated string of key and value. 首先,将映射中的每个条目映射到单个字符串 - 键和值的串联字符串。 Once you have that, you can simply use the reduce() method or collect() method to do it. 一旦你有了,你可以简单地使用reduce()方法或collect()方法来做到这一点。

Code snippet using 'reduce()' method will look something like this: 使用'reduce()'方法的代码段看起来像这样:

    Map<String, String> 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);

This will give you the following output: 这将为您提供以下输出:

sam2 : sam2 , sam1 : sam1

You can also use the collect()' method instead of reduce()` method. 您也可以使用collect()' method instead of reduce()`方法。 It will look something like this: 它看起来像这样:

    String concatString = map.entrySet()
            .stream()
            .map(element-> element.getKey().toString() + " : " + element.getValue().toString())
            .collect(Collectors.reducing("", (str1,str2) -> str1 + " , " + str2)).substring(3);

Both methods give the same output. 两种方法都提供相同的输出。

Consider slight change to @Eran 's code, with regard to the fact that HashMap.Entry.toString() already does joining by = for you: 考虑到@Eran的代码略有变化,关于HashMap.Entry.toString HashMap.Entry.toString()已为您加入=的事实:

String sorted =
    map.entrySet().stream()
        .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
        .map(Objects::toString)
        .collect(Collectors.joining(","));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM