【发布时间】:2016-11-06 14:17:59
【问题描述】:
我正在尝试删除所有空值,但如果最后一个键的 treeSet 为空,那么它仍然存在。所以我在想如果最后一个条目为空,如何删除它。由于这是一个treeMap,我认为我可以通过使用 tm.lastKey() 访问它来获取最后一个元素,但该方法似乎不存在。所以这个问题是双重的。首先,有没有办法删除包括最后一个在内的所有空值,第二个是 .lastKey() 方法在哪里?
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();
}
}
}
【问题讨论】:
-
不要使用原始类型。
-
您的
tm是Map<>。TreeMap的方法自然不会显示在上面。
标签: java dictionary treemap