Java 使用 lambda 将 Map 格式化为 String

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30237577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:21:54  来源:igfitidea点击:

Using lambda to format Map into String

javadictionarylambdajava-8

提问by TEXHIK

I have a map with Integerkeys and values. I need to transform it into a Stringwith this specific format: key1 - val1, key2 - val2, key3 - val3. Now, I'm using forEachto format each element, collect them into a List, and then do String.join();

我有一个带有Integer键和值的地图。我需要将它转换为String具有这种特定格式的:key1 - val1, key2 - val2, key3 - val3. 现在,我使用forEach格式化每个元素,将它们收集到一个列表中,然后执行 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.

有没有更短的方法来做到这一点?用 lambda 来做这件事会很好,因为我需要一些使用 lambda 的练习。

采纳答案by Jon Skeet

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.joiningis a method which returns a Collectorwhich can work on an input sequence of strings, giving a result of a single string.
  • entrySet()获取一个可迭代的条目序列
  • stream()为该可迭代对象创建一个流
  • map()将该条目流转换为“键-值”形式的字符串流
  • collect(Collectors.joining(", "))将流中的所有条目连接成一个字符串,", "用作分隔符。Collectors.joining是一种返回 a 的方法,Collector它可以处理输入的字符串序列,给出单个字符串的结果。

Note that the order is notguaranteed here, because HashMapisn't ordered. You might want to use TreeMapto get the values in key order.

请注意,这里保证顺序,因为HashMap不是有序的。您可能希望使用TreeMap来按键顺序获取值。