Home > Mobile >  Add multiple elements to Object in Java
Add multiple elements to Object in Java

Time:12-02

I use the following map for enums and add an enum as shown below:

final Map<String, Object> enums = new HashMap<>();

enums.put("ZoneIds", gmtValues());

The ZoneIds enum has a List<String> returned from this method:

private static List<String> gmtValues() {
        return  ... // code omitted for brevity
    }


private static List<String> gmtNames() {
        return  ... // code omitted for brevity
    }

However, I want to pass another list in the same Object and then retrieve these 2 passed values in the frontend as ZoneIds.value and ZoneIds.name. So, how can I do this?

CodePudding user response:

The following options are possible:

  • "ZoneIds" is a list of lists, with name and value properly ordered by index
{"ZoneIds": [["name1", "value1"], ["nameN", "valueN"]]}

Then names/values are joined like this assuming that the sizes of lists returned by gmtNames() and gmtValues() are equal:

List<String> names = gmtNames();
List<String> values = gmtValues();
List<List<String>> nameValueList = IntStream.range(0, Math.min(names.size(), values.size()))
    .mapToObj(i -> Arrays.asList(names.get(i), values.get(i)))
    .collect(Collectors.toList());
enums.put("ZoneIds", nameValueList);

  • "ZoneIds" is a list of maps:
{"ZoneIds": [{"name":"name1", "value":"value1"}, {"name":"nameN", "value":"valueN"}]}
List<Map<String, String>> listMaps = IntStream.range(0, Math.min(names.size(), values.size()))
    .mapToObj(i -> Map.of("name", names.get(i), "value", values.get(i)))
    .collect(Collectors.toList());
enums.put("ZoneIds", listMaps);

  • Simple map, with key taken from gmtNames() list:
{"ZoneIds": {"name1":"value1", "nameN":"valueN"}}
Map<String, String> nameValueMap = IntStream.range(0, Math.min(names.size(), values.size()))
    .boxed()
    .collect(Collectors.toMap(
        names::get,    // key from names list
        values::get,   // value from values list
        (v1, v2) -> v1, // merge function in case of conflicts
        LinkedHashMap::new // keep insertion order
    ));
enums.put("ZoneIds", nameValueMap);

  • Related