java map的格式化,使用lambda将Map格式化为String

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 ships = new ArrayList<>(4);

for (Map.Entry 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.

解决方案

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 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值