Home > other >  Getting values from map stream sorted in Java
Getting values from map stream sorted in Java

Time:12-13

I have a map values than I can sort and print in console using:

map_serv.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .forEach(System.out::println);

The output its like:

Value1=1
Value2=3
Value3=432
Value4=1000

The method forEach gives that messsage:

required: Consumer<? super Entry<String,Long>>

But I dont want to get the map printed in console, I want the values in a variable or/and printed in a jTxtPane Document

docKO.insertString(docKO.getLength(), EACH ITEM);

CodePudding user response:

The forEach method takes a consumer function, which takes in an Entry. The println method takes in an Object, so the arguments match. Here's an example on how to use the forEach method in your use case:

map_serv.entrySet().stream()
            .sorted(Map.Entry.comparingByValue())
            .forEach((entry) -> {
                docKO.insertString(docKO.getLength(), entry.getKey() " = " entry.getValue());
            });

This will put each entry in the map into your document, in the key = value format. If you want to change the format, just change the consumer to do something else with the entry.

CodePudding user response:

forEach is a terminating operation: It "makes the stream go" and the stuff that falls out of the end of it is 'handled' by invoking the code you pass to it (in this case, x -> System.out.println(x)) on each element.

What you now want instead is a different kind of terminator: One that combines everything falling out of the stream into a single value. Hence, this is called a collector - it collects all values into a single thing.

There are various collectors in the Collectors class; many of those take in methodrefs/closures themselves.

The one that seems relevant here is Collectors.joining, which requires specifically a stream of strings, and will combine them by concatenating them. You can specify optional prefix, suffix, and infixes (i.e. to turn 5, 2, and 10 into the string [5, 2, 10], prefix = [, infix = , , suffix = ]). Thus, you first map your data to a string, and then collect that using a string joiner collector, obtained by invoking Collectors.joining which makes one for you.

Thus:

String v = mapServ.entrySet().stream()
  .sorted(Map.Entry.comparingByValue())
  .map(e -> e.getKey()   "="   e.getValue())
  .collect(Collectors.joining("\n"));

assertEquals("""
  Value1=1
  Value2=3
  Value3=432
  Value4=1000
""", v);

CodePudding user response:

You can try this:

String response = map_serv.entrySet().stream()
        .sorted(Map.Entry.comparingByValue())
        .map(e -> String.format("%s=%s", e.getKey(), e.getValue()))
        .collect(Collectors.joining("\n"));
  • Related