Search code examples
javahashmap

Map need to be filter without tmst values


In the below map, I have to remove key and values if key contains "tmst"

Input Map:

{"sun":"test", "row_mod_tmst":"10:05:20", "when" :"yesterday"}

Output Map:

{"sun":"test", "when" :"yesterday"}

I have tried like below, It is not working

 Map<String, Object> withoutTMST = map.entrySet().stream().filter(entry -> (!entry.getKey().endsWith("tmts"))).
                    collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Solution

  • I would just remove those entries from the map, instead of creating a new map object.

    Collection#removeIf is a good candidate for this, applied on the map's entrySet().

    As for the removal condition, I would use contains in conjunction with toLowerCase().

    Here's the code for that:

    map.entrySet().removeIf(entry -> entry.getKey().toLowerCase().contains("tmst"));
    

    Input:

    { sun=test, row_mod_tmst=10:05:20, when=yesterday }
    

    Output:

    { sun=test, when=yesterday }