earl
earl

Reputation: 768

Remove a key from a nested map in Java

I have a map object whose value is:

{Name={
    Id=9999, 
    status=OK, 
    Idn={
        source=TEST, 
        value=123, 
        TS=2018-11-14T18:10:33.998Z
    }
}}

I have to remove the value=123 part from it so that my final Map looks like:

{Name={
    Id=9999, 
    status=OK, 
    Idn={
        source=TEST, 
        TS=2018-11-14T18:10:33.998Z
    }
}}

the .remove(key) part would work on "Name" tag but I am unable to reach the nested Name.Idn.value and remove it.

Edited code: My map is populated from mongoTemplate.findOne()

Map<String, Map<String, Object>> response    
Query query = new Query();
    Criteria criteria = Criteria.where("Name.Idn.value").is(123);
    query.addCriteria(criteria).fields().exclude("_id");
    response = mongoTemplate().findOne(query, Map.class, "dummy_col");

From response, while sending response back, the Name.Idn.value is to be removed.

Upvotes: 0

Views: 1588

Answers (2)

azro
azro

Reputation: 54148

I'd guess you have a Map<String, Object> map to be able to hold such different types as values, so you need to case first value as Map<String, Map> to be able to continue your path

((Map<String, Map<String, Object>>) map.get("Name")).get("idn").remove("source"); 

In fact yo have a Map<String, Map<String, Object>> map, so you know the first get() will return a Map, this is the second one that you need to cast

((Map<String, Object>) map.get("Name").get("idn")).remove("source");

Upvotes: 1

Lev M.
Lev M.

Reputation: 6269

You seem to have 3 levels of nested maps.

The value of name is a map, which has a key Idn with value that is also a map.

So, you would need a code that would look like this:

Map<String, Map<>> top = { ... };
Map<String, Map<>> name = top.get("Name");
Map<String, String> idn = name.get("Idn");

idn.remove("value");

You could also do it in one line like this:

Map <String, Map> top = { ... };

top.get("Name").get("Idn").remove("value");

Upvotes: 1

Related Questions