Hesam Hesam - 7 months ago 12
Java Question

java - How to remove all null elements from a Map?

The simplest form of question is I have a collection and I want to delete/remove all elements that their

value == null
. I don't want delete in place (I want to get new Map so my original Map is safe).

public Map<String, String> ADDITIONAL_QUERY = new HashMap<>();
this.ADDITIONAL_QUERY.put("deviceManufacturer", payload.getManufacturer());
this.ADDITIONAL_QUERY.put("deviceModel", payload.getModel());
this.ADDITIONAL_QUERY.put("source", payload.getSource());
this.ADDITIONAL_QUERY.put("adrIMEI", payload.getIMEI());
this.ADDITIONAL_QUERY.put("adrMEID", payload.getMEID());
this.ADDITIONAL_QUERY.put("adrUDID", payload.getUuid() == null ? null : payload.getUuid().toString());
this.ADDITIONAL_QUERY.put("adrID", payload.getAndroidId());
this.ADDITIONAL_QUERY.put("adrSERIAL", payload.getSerial());

I add more elements to ADDITIONAL_QUERY depends of what API I'm calling later.

More details:
I just upgraded my Retrofit lib to version 2.0. I have
@FieldMap Map<String, String> additionalQuery
in majority of my APIs (around 100 APIs). According to their doc regard
,"Named key/value pairs for a form-encoded request. A null value for the map, as a key, or as a value is not allowed.", as mentioned on java doc (It's so funny that their doc on web says you can https://square.github.io/retrofit/2.x/retrofit/index.html?retrofit2/http/class-use/FieldMap.html).
enter image description here

As APIs are getting called a lot, I'm looking for a way with minor overhead and fast of course. Any idea would be appreciated thanks.


If you have Guava, you can create a filtered view to avoid copying to a new map:

Map<String, String> filtered = Maps.filterValues(ADDITIONAL_QUERY, new Predicate<String>() {
    public boolean apply(String value) {
        return value != null;