[英]convert map to list<string> - as “key-value” to each list entry
I want to convert Map<Integer, String>
to List<String>
with each map entry - to 1 entry in the list as "key - value"我想使用每个映射条目将
Map<Integer, String>
转换为List<String>
- 将列表中的 1 个条目作为“键 - 值”
I searched and I only found to map values only to 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");
I want this to be mapped to list as我希望将其映射到列表中
"10-apple"
"20-orange"
and so on.等等。
this can be done easily if I used foreach .. but I want to know if it is feasible to get it through streams如果我使用 foreach ,这可以轻松完成 .. 但我想知道通过流获取它是否可行
List<String> list = map.entrySet()
.stream()
.map(entry -> entry.getKey() + "-" + entry.getValue())
.sorted()
.collect(Collectors.toList());
Here is one variant using .map to move from list to map这是使用 .map 从列表移动到地图的一种变体
List<String> list = map.entrySet()
.stream()
.map(x -> String.format("%d-%s", x.getKey().intValue(), x.getValue()))
.sorted().collect(Collectors.toList());
Just a slightly different variant to the other answers.只是与其他答案略有不同的变体。 if the insertion/iteration order is important then I'd rather use a
LinkedHashMap
in the first place as opposed to using a HashMap
then sorting it which is actually not always guaranteed to work.如果插入/迭代顺序很重要,那么我宁愿首先使用
LinkedHashMap
而不是使用HashMap
然后对其进行排序,这实际上并不总是保证工作。
Example:例子:
Map<Integer, String> map = new LinkedHashMap<>();
...
...
...
then stream over the entrySet and collect to a list implementation:然后流过 entrySet 并收集到列表实现:
List<String> list = map.entrySet()
.stream()
.map(e -> e.getKey() + "-" + e.getValue())
.collect(Collectors.toList());
if you want just the values of the Map try this如果你只想要 Map 的值试试这个
List<String> list = new ArrayList<>(map.values())
{"apple", "orange"} {“苹果”,“橙色”}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.