Convert Stream to String in Java
Asked Answered
M

3

16

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();
}
Mcginley answered 4/7, 2019 at 10:10 Comment(2)
Can you give us a sample map, along with what the string output should be?Housebreaker
I think you're getting confused here between Java's two (confusingly-named) different types of 'stream'. You should be able achieve your objective much more simply, without all the BufferedReader stuff, if you just look at Collectors.joining().Iver
P
22

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 (","));
Ploy answered 4/7, 2019 at 10:15 Comment(0)
S
2

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(","));
Sudarium answered 4/7, 2019 at 11:47 Comment(1)
I would recommend against this .The API documentation for Map.Entry (which is what entrySet is defined to return a Set of) does not specify the format for toString. Since it is not a documented part of the API, different or future versions of Java could deviate from this format without breaking the API contract.Sulfaguanidine
R
1

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 ofreduce()` 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.

Renege answered 4/7, 2019 at 11:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.