在 Java 中檢索 TreeMap 中的最後一個條目


使用 TreeMap 中的 lastEntry() 方法檢索最後一個條目。

建立 TreeMap 並新增一些元素 −

TreeMap<Integer,String> m = new TreeMap<Integer,String>();
m.put(1,"India");
m.put(2,"US");
m.put(3,"Australia");
m.put(4,"Netherlands");
m.put(5,"Canada");

現在,檢索最後一個條目 −

m.lastEntry()

以下是在 TreeMap 中檢索最後一個條目的示例 −

示例

 線上演示

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      TreeMap<Integer,String> m = new TreeMap<Integer,String>();
      m.put(1,"India");
      m.put(2,"US");
      m.put(3,"Australia");
      m.put(4,"Netherlands");
      m.put(5,"Canada");
      for(Map.Entry e:m.entrySet()) {
         System.out.println(e.getKey()+" "+e.getValue());
      }
      System.out.println("Last Entry in Map is "+m.lastEntry());
   }
}

輸出

1 India
2 US
3 Australia
4 Netherlands
5 Canada
Last Entry in Map is 5=Canada

更新時間:30-Jul-2019

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得證書

開始
廣告
© . All rights reserved.