I have a map with Integer
keys and values. I need to transform it into a String
with this specific format: key1 - val1, key2 - val2, key3 - val3
. Now, I'm using forEach
to format each element, collect them into a List, and then do String.join();
List<String> ships = new ArrayList<>(4); for (Map.Entry<Integer, Integer> entry : damagedMap.entrySet()) { ships.add(entry.getKey() + " - " + entry.getValue()); } result = String.join(",", ships);
Is there any shorter way to do it? And it would be good to do it with lambda, because I need some practice using lambdas.
Use Object#toString() . String string = map. toString();
A free variable can be a constant or a variable defined in the enclosing scope of the function. The lambda function assigned to full_name takes two arguments and returns a string interpolating the two parameters first and last .
Get Elements From a Java Map Map map = new HashMap(); map. put("key1", "value 1"); String element1 = (String) map. get("key1"); Notice that the get() method returns a Java Object , so we have to cast it to a String (because we know the value is a String).
I think you're looking for something like this:
import java.util.*; import java.util.stream.*; public class Test { public static void main(String[] args) throws Exception { Map<Integer, String> map = new HashMap<>(); map.put(1, "foo"); map.put(2, "bar"); map.put(3, "baz"); String result = map.entrySet() .stream() .map(entry -> entry.getKey() + " - " + entry.getValue()) .collect(Collectors.joining(", ")); System.out.println(result); } }
To go through the bits in turn:
entrySet()
gets an iterable sequence of entriesstream()
creates a stream for that iterablemap()
converts that stream of entries into a stream of strings of the form "key - value"collect(Collectors.joining(", "))
joins all the entries in the stream into a single string, using ", "
as the separator. Collectors.joining
is a method which returns a Collector
which can work on an input sequence of strings, giving a result of a single string.Note that the order is not guaranteed here, because HashMap
isn't ordered. You might want to use TreeMap
to get the values in key order.
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