Reputation: 11
Like title says how do I remove the Last entry in a treemap if it's sorted by <Integer, String>
since the remove()
method in treemap only delete` a key...
Look like this:
int i = 0;
while (i <= 10) {
System.out.println("Value is: " + Resultat.lastEntry());
i++;
// here, I want to delete the last entry
}
Upvotes: 0
Views: 1784
Reputation: 958
Full code is here
int j = 0;
while (j <= 3) {
Map.Entry<Integer,String> entry = records.pollLastEntry();
records.remove(entry.getKey());
j++;
}
Upvotes: 0
Reputation: 16067
Why don't you use pollLastEntry()
?
Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
public static void main (String[] args) throws java.lang.Exception
{
TreeMap<Integer, String> testTreeMap = new TreeMap<>();
//Populate example map with values
testTreeMap.put(1,"Test");
testTreeMap.put(0, "Test0");
testTreeMap.put(6, "Test6");
testTreeMap.put(4, "Test4");
testTreeMap.put(2, "Test2");
testTreeMap.put(3, "Test3");
testTreeMap.put(5, "Test5");
int i = 0;
while (i <= 3) {
System.out.println("Value is: " + testTreeMap.pollLastEntry());
i++;
}
System.out.println(testTreeMap);
}
Output :
Value is: 6=Test6
Value is: 5=Test5
Value is: 4=Test4
Value is: 3=Test3
{0=Test0, 1=Test, 2=Test2}
Upvotes: 0
Reputation: 21961
Use NavigableMap.pollLastEntry -removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
NavigableMap<Integer, String> map=new TreeMap<>();
map.put(1, "one");
System.out.println(map);
map.pollLastEntry(); // It wil remove last entry.
System.out.println(map);
Upvotes: 1
Reputation: 35557
You can just use map.remove()
; if you know the key of the last key value pair.
Map<Integer,String> map=new TreeMap<>();
map.remove("key");// key of last entry.
Upvotes: 0