Is it possible for us to implement a HashMap with one key and two values. Just as HashMap?
Please do help me, also by telling (if there is no way) any other way to
Just for the record, the pure JDK8 solution would be to use Map::compute
method:
map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);
Such as
public static void main(String[] args) {
Map> map = new HashMap<>();
put(map, "first", "hello");
put(map, "first", "foo");
put(map, "bar", "foo");
put(map, "first", "hello");
map.forEach((s, strings) -> {
System.out.print(s + ": ");
System.out.println(strings.stream().collect(Collectors.joining(", ")));
});
}
private static void put(Map> map, KEY key, VALUE value) {
map.compute(key, (s, strings) -> strings == null ? new ArrayList<>() : strings).add(value);
}
with output:
bar: foo
first: hello, foo, hello
Note that to ensure consistency in case multiple threads access this data structure, ConcurrentHashMap
and CopyOnWriteArrayList
for instance need to be used.