java – Map的Collectors.toMap>无法解析
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Map的Collectors.toMap>无法解析,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1565字,纯文字阅读大概需要3分钟。
内容图文
我有这个代码的和平工作正常,需要一个Map< String,List< Device>>并排序时间并返回相同的数据结构:
Stream<Map.Entry<String, List<Device>>> results = device.getDeviceMapList().entrySet().stream();
Map<String, List<Device>> sortedMap = new HashMap<String, List<Device>>();
results.forEach(e -> {
e.getValue().sort(Comparator.comparing(Device::getStationTimeStamp));
sortedMap.put(e.getKey(), e.getValue());
});
现在我尝试使用Collectors.toMap并没有成功:
Map<String, List<Device>> sortedMap = results.forEach(e -> {
e.getValue().stream()
.sorted(Comparator.comparing(Device::getStationTimeStamp))
.collect(Collectors.toMap(e.getKey(), ArrayList<Device>::new));
});
部分.collect(Collectors.toMap(e.getKey(),ArrayList< Device> :: new));是我试过的,它不完全正确,我做错了什么?
解决方法:
为了重现您的问题,我创建了一个示例Map
Map<Integer, List<Integer>> mapA = new HashMap<>();
mapA.put(1, Arrays.asList(1,2,3,4,5,8,7,6,9));
mapA.put(2, Arrays.asList(1,2,3,5,4,6,7,8,9));
mapA.put(3, Arrays.asList(2,3,1,4,5,6,7,8,9));
mapA.put(4, Arrays.asList(1,2,8,4,6,5,7,3,9));
mapA.put(5, Arrays.asList(9,2,3,4,5,6,7,8,1));
并把它变成了与你相似的流
Stream<Map.Entry<Integer, List<Integer>>> results = mapA.entrySet().stream();
您可能已经注意到,mapA中的列表未排序.
获取Map< Integer,List< Integer>>将List排序后,您可以执行以下操作
Map<Integer,List<Integer>> sortedMap =
results.collect(Collectors.toMap(s -> s.getKey(),
s -> s.getValue().stream()
.sorted(Comparator.naturalOrder()).collect(Collectors.toList())));
您必须使用Comparator.comparing(Device :: getStationTimeStamp)替换Comparator.naturalOrder().
内容总结
以上是互联网集市为您收集整理的java – Map的Collectors.toMap>无法解析全部内容,希望文章能够帮你解决java – Map的Collectors.toMap>无法解析所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。