如何使用Java streams创建地图站点列表
从以下地图开始:如何使用Java streams创建地图站点列表,java,java-stream,Java,Java Stream,从以下地图开始: Map<Integer, String> mapList = new HashMap<>(); mapList.put(2,"b"); mapList.put(4,"d"); mapList.put(3,"c"); mapList.put(5,"e"); mapList.put(1,"a"); mapList
Map<Integer, String> mapList = new HashMap<>();
mapList.put(2,"b");
mapList.put(4,"d");
mapList.put(3,"c");
mapList.put(5,"e");
mapList.put(1,"a");
mapList.put(6,"f");
Map-mapList=newhashmap();
地图一览表.付诸表决(2,“b”);
地图一览表.付诸表决(4,“d”);
地图列表.付诸表决(3,“c”);
地图列表。将(5,“e”);
地图列表.付诸表决(1,“a”);
地图列表。放置(6,“f”);
我可以使用以下流对地图进行排序:
mapList.entrySet()
.stream()
.sorted(Map.Entry.<Integer, String>comparingByKey())
.forEach(System.out::println);
mapList.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.forEach(System.out::println);
但我需要得到相应排序元素的列表(和一个字符串)(即:abcdef),它们确实与键1、2、3、4、5、6对应
我找不到在该Stream命令中执行此操作的方法
谢谢
正如@MA在他的评论中所说,我需要一个映射,这在这个问题中没有解释:
所以非常感谢你@MA
有时候,人们太快就要结束提问了 您可以使用映射收集器:
var sortedValues = mapList.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.mapping(Entry::getValue, Collectors.toList()))
您可以使用映射收集器:
var sortedValues = mapList.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.mapping(Entry::getValue, Collectors.toList()))
如果要对键进行排序并仅收集值,则需要使用映射函数仅在排序后保留值。之后,您可以收集或执行foreach循环
mapList.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.collect(Collectors.toList());
如果要对键进行排序并仅收集值,则需要使用映射函数仅在排序后保留值。之后,您可以收集或执行foreach循环
mapList.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.collect(Collectors.toList());
您还可以使用一些不同的集合类而不是流:
List List=newarraylist(newtreemap(mapList).values());
缺点是,如果你在一行中完成所有这些,它可能会变得非常混乱,非常快。此外,您正在丢弃中间的
TreeMap
,仅用于排序。您还可以使用一些不同的集合类,而不是流:
List List=newarraylist(newtreemap(mapList).values());
缺点是,如果你在一行中完成所有这些,它可能会变得非常混乱,非常快。此外,您丢弃中间的
TreeMap
只是为了排序。查看map
方法将条目转换为值,然后collect
将其转储到列表中。mapList.entrySet().stream().sorted(map.entry.comparingByKey()).collector(collector.mapping(entry::getValue,Collectors.toList())
非常感谢@MA这正是我想要的。我不知道如何在入门级使用collect进行映射,我不知道在关闭我的问题中如何解释这一点。。。。事实上,副本并不是最好的,重新打开并添加了我的评论作为答案。相关:,您只需从回答中切换getKey
和getValue
,查看map
方法将条目转换为值,然后collect
将其转储到列表中。mapList.entrySet().stream()(Map.Entry.comparingByKey()).collect(Collectors.mapping(Entry::getValue,Collectors.toList()))
非常感谢@MA,这正是我想要的。我不知道如何在入门级使用collect进行映射,我也不知道在关闭我的问题中如何解释这一点……事实上,副本并不是最好的,重新打开并添加了我的注释作为答案。相关:,您只需切换getKey
和getValue
从这个答案开始为简单起见,我甚至会使用.map(Entry::getValue).collect(Collectors.toList())
。映射()
collector更应该用于@Lino是的,这也可以,但我不确定底层实现是否有差异。为了简单起见,我甚至会使用.map(Entry::getValue).collector(collector.toList())
。映射()
collector应该用于@Lino是的,这也可以,但我不确定底层实现中是否存在差异。