i squared - Keep it Real i squared - Keep it Real - 5 months ago 12
Java Question

Deleting the treeMap entries with null values

I am attempting to remove all the nulls, but if the last key's treeSet is null then it remains there. So I was thinking how to delete the last entry if it is null. Since this is a treeMap I thought that I can obtain the last element by accessing it with tm.lastKey() but that method does not seem to exist. So this question is twofold. First, is there a way to delete all the nulls including the last one and the second is, where is the .lastKey() method?

public class Timing {
private static Map<String, SortedSet> tm = new TreeMap<String, SortedSet>();

public static Map manipulate() {
SortedSet ss = new TreeSet();
ss.add("APPL");
ss.add("VOD");
ss.add("MSFT");

tm.put("2019-09-18",null);
tm.put("2019-09-21",ss);
tm.put("2019-09-22", null);
tm.put("2019-09-20",ss);
tm.put("2019-09-19", null);
tm.put("2019-09-23",null);

return tm;
}

public static void printMap() {
for (String s: tm.keySet()) {
System.out.println(s + ": " + tm.get(s));
}
}

// Will delete all but the last one
public static void deleteNull() {
Set set = tm.entrySet();
Iterator i = set.iterator();
Map.Entry me = (Map.Entry) i.next();
// there is no tm.lastKey()??
while(i.hasNext()) {
if (me.getValue() == null) {
i.remove();
}
me = (Map.Entry) i.next();
}
}
}

Answer

To remove all entries with a value of null from your map you can replace the deleteNull method with

tm.values().removeIf(Objects::isNull);