将映射转换为list <string>-作为每个列表项的“键值”

我想将 每个地图条目转换Map<Integer, String>为List<String>-列表中的1个条目作为“键-值”


我进行了搜索,但只发现将值仅映射到List。


Map<Integer, String> map = new HashMap<>();

    map.put(10, "apple");

    map.put(20, "orange");

    map.put(30, "banana");

    map.put(40, "watermelon");

    map.put(50, "dragonfruit");

我希望将其映射为列表为


 "10-apple" 

 "20-orange"

等等。


如果我使用foreach,可以很容易地做到这一点,但是我想知道通过流获取它是否可行


冉冉说
浏览 122回答 3
3回答

FFIVE

这是使用.map从列表移动到地图的一种变体List<String> list = map.entrySet()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(x -> String.format("%d-%s", x.getKey().intValue(), x.getValue()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.sorted().collect(Collectors.toList());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java