Java - 投射地图
如何以最简洁的方式将 Map
转换为 Map
?
有没有办法在不迭代地图的情况下做到这一点?
谢谢
How can I cast a Map<Object,Object>
to Map<String,String>
in the cleanest way?
Is there a way to do that without iterating over the map?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
实际的答案是:
The actual answer is:
我认为解释为什么简单的解决方案不起作用以及为什么你永远不应该使用它是一个好主意。
假设您可以将
List
现在您确实可以使用 Bohemians/Chris 解决方案破解它,但您基本上会破坏 Java 的类型系统。 不要这样做。您不希望
List
包含整数!稍后进行有趣的调试 - 循环遍历所有变量的附加代码将避免很多令人头疼的问题,而且几乎不是性能问题。如果有理由将 Map 声明为采用对象而不是字符串,那么有人可能会向其中添加任何对象 - 通常您应该能够使用更好的泛型来避免这种情况。
I think it's a good idea to explain why the simple solution doesn't work and why you never, ever should use this.
Assume you could cast
List<Object>
toList<String>
(the same applies to Map, just a simpler interface). What would you expect to happen from the following code:Now you CAN hack it indeed using Bohemians/Chris solution, but you basically destroy Java's type system. DON'T DO THAT. You don't want a
List<String>
to contain an Integer! Have fun debugging that later on - the additional code of looping through all variables will avoid lots of headaches and hardly is a performance problem.If there's a reason to declare the Map as taking an Object instead of a String someone may add any object to it - usually you should be able to avoid this with a better generic.
想要干净,就必须“深度”转换!键和值。
使用 Java 8 流,只需几行:
If you want something clean, you must convert "deeply"! keys and values.
Using Java 8 stream, this take only a few lines:
基于 Chris J 的回答,这是他的“黑客”代码,显示了它有效:
哇!没有运行时异常:)
Building on Chris J's answer, here's his "hack" code in action, showing it works:
Wow! No runtime exceptions :)