淺談Java中Map和Set之間的關(guān)系(及Map.Entry)
1、通過查找API文檔:

2、Map.Entry是一個接口,所以不能直接實例化。

3、Map.entrySet( )返回的是一個collection集合,并且,這個collection中的元素是Map.Entry類型,如下圖所示:


4、
Map是Java中的接口,Map.Entry是Map的一個內(nèi)部接口。java.util.Map.Entry接口主要就是在遍歷map的時候用到。
Map提供了一些常用方法,如keySet()、entrySet()等方法,keySet()方法返回值是Map中key值的集合;entrySet()的返回值也是返回一個Set集合,此集合的類型為Map.Entry。
Map.Entry是Map聲明的一個內(nèi)部接口,此接口為泛型,定義為Entry<K,V>。它表示Map中的一個實體(一個key-value對)。接口中有g(shù)etKey(),getValue方法。
package Demo;
import java.util.*;
import java.util.Map.*;
public class DemoMap {
public static void main(String[] args) {
text1();
System.out.println("=========================================================");
text2();
}
public static void text1(){
Map<Integer,String> DemoMap=new HashMap<Integer,String>();
DemoMap.put(4, "dddd");
DemoMap.put(1, "a");
DemoMap.put(3, "ccc");
DemoMap.put(2, "bb");
Collection<Map.Entry<Integer,String>> set=DemoMap.entrySet();
System.out.println("set=="+set);
Iterator<Map.Entry<Integer, String>> it=set.iterator();
Map.Entry<Integer,String> entry;
while(it.hasNext()){
entry=it.next();
System.out.println("en.getKey()=="+entry.getKey());
System.out.println("en.getValue()=="+entry.getValue());
}
}
public static void text2(){
Map<Integer,String> DemoMap=new LinkedHashMap<Integer,String>();
DemoMap.put(4, "dddd");
DemoMap.put(1, "a");
DemoMap.put(3, "ccc");
DemoMap.put(2, "bb");
Iterator<Entry<Integer,String>> set=DemoMap.entrySet().iterator();
Entry<Integer,String> temp;
while(set.hasNext()){
temp=set.next();
System.out.println("getKey()=="+temp.getKey());
System.out.println("getValue()=="+temp.getValue());
}
}
}
輸出結(jié)果為:

以上這篇淺談Java中Map和Set之間的關(guān)系(及Map.Entry)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java語言實現(xiàn)簡單FTP軟件 FTP遠程文件管理模塊實現(xiàn)(10)
這篇文章主要為大家詳細介紹了Java語言實現(xiàn)簡單FTP軟件,F(xiàn)TP遠程文件管理模塊的實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04
Java中計算集合中元素的出現(xiàn)次數(shù)統(tǒng)計
本文主要介紹了Java中計算集合中元素的出現(xiàn)次數(shù)統(tǒng)計,使用Collections類配合HashMap來統(tǒng)計和java lamb 計算這兩種方式,具有一定的參考價值,感興趣可以了解一下2024-02-02
Spring ApplicationListener的使用詳解
這篇文章主要介紹了Spring ApplicationListener的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06

