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 (","));
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(","));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With