简体   繁体   中英

Create mutable collections (Map.of and List.of)

Looks like Map.of() and List.of() both create immutable collections. That's useful, but I am looking for a way to create mutable collections sometimes using a factory method.

When I try: HashMap.of() I get this error:

Static method may be invoked on containing interface class only

HashMap has a constructor that can take another Map , so you can create a HashMap by passing it whatever Map.of(...) produces:

HashMap<String, String> map = new HashMap<>(Map.of("k1", "v1", "k2", "v2"));

Likewise for ArrayList and List.of(...) .

I use a custom method inside of the utils class. Please try, it works correctly.

public static Map<String, Object> mutableMap(Object... args) {
        return IntStream.iterate(0, i -> i < args.length, i -> i + 2)
                        .filter(i -> i + 1 < args.length)
                        .boxed()
                        .collect(toMap(i -> (String) args[i], i -> args[i + 1], (a, b) -> b, HashMap::new));
}

Also, you can add validation on paired number of arguments OR add logic to replace the 'null' value according to your requires.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM