HashMap with multiple values under the same key

前端 未结 22 1869
旧时难觅i
旧时难觅i 2020-11-22 06:49

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

22条回答
  •  心在旅途
    2020-11-22 07:07

    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.

提交回复
热议问题