Using lambda to format Map into String

后端 未结 1 1454
太阳男子
太阳男子 2020-12-24 00:36

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 - v

相关标签:
1条回答
  • 2020-12-24 01:25

    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 entries
    • stream() creates a stream for that iterable
    • map() 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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题