Convert Stream to String in Java

Edoardo Tavilla :

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();
}
Eran :

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 (","));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=121539&siteId=1