使用lambda将Map格式化为String [英] Using lambda to format Map into String

查看:460
本文介绍了使用lambda将Map格式化为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张带整数键和值的地图。我需要使用以下特定格式将其转换为 String key1 - val1,key2 - val2,key3 - val3 。现在,我使用 forEach 格式化每个元素,将它们收集到List中,然后执行String.join();

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);

有没有更短的方法呢?用lambda做这件事会很好,因为我需要练习使用lambdas。

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.

推荐答案

我觉得你在找对于这样的事情:

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);
    }
}

依次查看位:


  • entrySet()获取可迭代的条目序列

  • stream()为该可迭代创建一个流

  • map()将该条目流转换为key - value形式的字符串流

  • collect(Collectors.joining(,))使用作为分隔符,将流中的所有条目连接成一个字符串。 收藏家.joining 是一个返回 收集器 ,它可以处理输入的字符串序列,给出单个字符串的结果。

  • 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.

请注意,此处的订单,因为 HashMap 未订购。您可能希望使用 TreeMap 来获取按键顺序排列的值。

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.

这篇关于使用lambda将Map格式化为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆