79541367

Date: 2025-03-28 12:04:43
Score: 0.5
Natty:
Report link

The old HashMap.put()

The modern methods of the standard library, including the methods in the stream package, don’t like nulls as keys or values in maps. So to obtain what you want, you may use the classic methods from the introduction of the Java collections framework in Java 1.2. It gets just a little wordier:

private static Map<String, Object> toParamMap(List<Map.Entry<String, Object>> params) {
    Map<String, Object> paramMap = new HashMap<>();
    params.forEach(param -> paramMap.put(param.getKey(), param.getValue()));
    return paramMap;
}

Trying it out with your example:

    List<Map.Entry<String, Object>> params = Arrays.asList(
            new AbstractMap.SimpleEntry<>("key1", 1),
            new AbstractMap.SimpleEntry<>("key2", null)
    );
    Map<String, Object> paramMap = toParamMap(params);
    System.out.println(paramMap);

Output is a map with a null value in it:

{key1=1, key2=null}

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Unregistered user (0.5):
  • Low reputation (1):
Posted by: Hiro Silva