简体   繁体   中英

Convert Stream to String in Java

I want to convert a Stream of a Map<> into a String, to append it to a textArea. I tried some methods, the last with StringBuilder, but they don't work.

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 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. 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.

Code snippet using 'reduce()' method will look something like this:

    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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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