我正在寻找一个“CLEAN & Simple”初始化ConcurrentHashMap的方法。Java 8 ConcurrentHashMap初始化
与Java 8我有这样的: -
private static final Map<String, String> myStreamedMap = Stream.of(
new AbstractMap.SimpleImmutableEntry<>("Key1", "Value1"),
new AbstractMap.SimpleImmutableEntry<>("Key2", "Value2"),
new AbstractMap.SimpleImmutableEntry<>("Key3", "Value3"),
new AbstractMap.SimpleImmutableEntry<>("Key4", "Value4")).
collect(Collectors.toMap((entry) -> entry.getKey(), (entry) -> entry.getValue()));
提供所期望的最终结果,但是我觉得
“new AbstractMap.SimpleImmutableEntry<>
”
使得它很难看怎么回事。
有什么办法可以“隐藏”这个并保持一条线?
UPDATE
想出了这个(明显)解决方案
private static final Map<String, String> myStreamedMapWith = Stream.of(
with("Key1", "Value1"),
with("Key2", "Value2"),
with("Key3", "Value3"),
with("Key4", "Value4")).
collect(Collectors.toMap((entry) -> entry.getKey(), (entry) -> entry.getValue()));
private static AbstractMap.SimpleImmutableEntry<String, String> with(final String key, final String value) {
return new AbstractMap.SimpleImmutableEntry<>(key, value);
}
提取您自己的方法来描述您的预期。例如:'mapOf(with(“foo”,“bar”),...,with(“key”,“value”));' –
@AndrewTobilko我在寻找一个“自我记录”解决方案,像Builder模式。然后我可以添加De Duplication。一个约束是我更喜欢标准的Java解决方案。 – Hector
使用'static {}'块?它不是单行的,但是通过字符数 – the8472