在 Java 中从键值对构建映射
可能的重复:
HashMap 构建器
是否有任何实用程序类允许从多个键值对创建 Map以方便且可读的方式?
我认为 guava 应该包含一些东西,但我找不到任何具有必要功能的东西。
我想要的是这样的:
MapBuilder.newHashMap()
.with("key1", 10)
.with("key2", 20)
.with("key3", 30)
.build();
PS 我也知道双括号方法 (new HashMap<>() {{ put(..); put(..); }}
) 但是我觉得它既不可读也不方便。
Possible Duplicate:
builder for HashMap
Are there any utility class which allows to create a Map from a number of key-value pairs in a convenient and readable manner?
I thought that guava
should have contain something but I couldn't find anything with necessary functionality.
What I want is something like this:
MapBuilder.newHashMap()
.with("key1", 10)
.with("key2", 20)
.with("key3", 30)
.build();
P.S. I also know about double-brace approach (new HashMap<>() {{ put(..); put(..); }}
) but I don't find it either readable or convenient.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有什么问题吗?
这对我来说看起来非常可读,而且我看不出您从 MapBuilder 中获得了什么。无论如何,这样的 MapBuilder 并不难实现。
What's wrong with
That looks very readable to me, and I don't see what you gain from your MapBuilder. Anyway, such a MapBuilder wouldn't be hard to implement.
为什么不自己推出呢?
Why not just roll your own?
使用返回
this
的 put 方法创建您自己的AbstractMap
怎么样?然后使用该方法来链接对:
How about creating your own
AbstractMap
with a put method that returnsthis
?Then use that method to chain pairs:
来自头部,未测试:
用法:
from head, not tested:
usage: