日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
有關(guān)于JavaMap,應(yīng)該掌握的8個(gè)問(wèn)題

 前言

最近幾天看了幾篇有關(guān)于Java Map的外國(guó)博文,寫得非常不錯(cuò),所以整理了Java map 應(yīng)該掌握的8個(gè)問(wèn)題,都是日常開發(fā)司空見(jiàn)慣的問(wèn)題,希望對(duì)大家有幫助;如果有不正確的地方,歡迎提出,萬(wàn)分感謝哈~

本章節(jié)所有代碼demo已上傳github

1、如何把一個(gè)Map轉(zhuǎn)化為L(zhǎng)ist

日常開發(fā)中,我們經(jīng)常遇到這種場(chǎng)景,把一個(gè)Map轉(zhuǎn)化為L(zhǎng)ist。map轉(zhuǎn)List有以下三種轉(zhuǎn)化方式:

  • 把map的鍵key轉(zhuǎn)化為list
  • 把map的值value轉(zhuǎn)化為list
  • 把map的鍵值key-value轉(zhuǎn)化為list

偽代碼如下:

 
 
 
 
  1.   // key list
  2.   List keyList = new ArrayList(map.keySet());
  3.   // value list
  4.   List valueList = new ArrayList(map.values());
  5.   // key-value list
  6.   List entryList = new ArrayList(map.entrySet());

示例代碼:

 
 
 
 
  1.   public class Test {
  2.       public static void main(String[] args) {
  3.           Map map = new HashMap<>();
  4.           map.put(2, "jay");
  5.           map.put(1, "whx");
  6.           map.put(3, "huaxiao");
  7.           //把一個(gè)map的鍵轉(zhuǎn)化為list
  8.           List keyList = new ArrayList<>(map.keySet());
  9.           System.out.println(keyList);
  10.          //把map的值轉(zhuǎn)化為list
  11.          List valueList = new ArrayList<>(map.values());
  12.          System.out.println(valueList);
  13.          把map的鍵值轉(zhuǎn)化為list
  14.          List entryList = new ArrayList(map.entrySet());
  15.          System.out.println(entryList);
  16.  
  17.      }
  18.  }

運(yùn)行結(jié)果:

 
 
 
 
  1.   [1, 2, 3]
  2.   [whx, jay, huaxiao]
  3.   [1=whx, 2=jay, 3=huaxiao]

2、如何遍歷一個(gè)Map

我們經(jīng)常需要遍歷一個(gè)map,可以有以下兩種方式實(shí)現(xiàn):

通過(guò)entrySet+for實(shí)現(xiàn)遍歷

 
 
 
 
  1.   for(Entry entry: map.entrySet()) {
  2.     // get key
  3.     K key = entry.getKey();
  4.     // get value
  5.     V value = entry.getValue();
  6.   }

實(shí)例代碼:

 
 
 
 
  1.   public class EntryMapTest {
  2.       public static void main(String[] args) {
  3.           Map map = new HashMap<>();
  4.           map.put(2, "jay");
  5.           map.put(1, "whx");
  6.           map.put(3, "huaxiao");
  7.   
  8.           for(Map.Entry entry: map.entrySet()) {
  9.               // get key
  10.              Integer key = (Integer) entry.getKey();
  11.              // get value
  12.              String value = (String) entry.getValue();
  13.  
  14.              System.out.println("key:"+key+",value:"+value);
  15.          }
  16.      }
  17.  }

通過(guò)Iterator+while實(shí)現(xiàn)遍歷

 
 
 
 
  1.   Iterator itr = map.entrySet().iterator();
  2.   while(itr.hasNext()) {
  3.     Entry entry = itr.next();
  4.     // get key
  5.     K key = entry.getKey();
  6.     // get value
  7.     V value = entry.getValue();
  8.   }

實(shí)例代碼:

 
 
 
 
  1.   public class IteratorMapTest {
  2.       public static void main(String[] args) {
  3.           Map map = new HashMap<>();
  4.           map.put(2, "jay");
  5.           map.put(1, "whx");
  6.           map.put(3, "huaxiao");
  7.   
  8.           Iterator itr = map.entrySet().iterator();
  9.           while(itr.hasNext()) {
  10.              Map.Entry entry = (Map.Entry) itr.next();
  11.              // get key
  12.              Integer key = (Integer) entry.getKey();
  13.              // get value
  14.              String value = (String) entry.getValue();
  15.  
  16.              System.out.println("key:"+key+",value:"+value);
  17.          }
  18.      }
  19.  }

運(yùn)行結(jié)果:

 
 
 
 
  1.   key:1,value:whx
  2.   key:2,value:jay
  3.   key:3,value:huaxiao

3、如何根據(jù)Map的keys進(jìn)行排序

對(duì)Map的keys進(jìn)行排序,在日常開發(fā)很常見(jiàn),主要有以下兩種方式實(shí)現(xiàn)。

把Map.Entry放進(jìn)list,再用Comparator對(duì)list進(jìn)行排序

 
 
 
 
  1.   List list = new ArrayList(map.entrySet());
  2.   Collections.sort(list, (Entry e1, Entry e2)-> {
  3.       return e1.getKey().compareTo(e2.getKey());
  4.   });

實(shí)例代碼:

 
 
 
 
  1.   public class SortKeysMapTest {
  2.       public static void main(String[] args) {
  3.           Map map = new HashMap<>();
  4.           map.put("2010", "jay");
  5.           map.put("1999", "whx");
  6.           map.put("3010", "huaxiao");
  7.   
  8.           List> list = new ArrayList<>(map.entrySet());
  9.           Collections.sort(list, (Map.Entry e1, Map.Entry e2)-> {
  10.                  return e1.getKey().toString().compareTo(e2.getKey().toString());
  11.          });
  12.  
  13.          for (Map.Entry entry : list) {
  14.              System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
  15.          }
  16.  
  17.      }
  18.  }

使用SortedMap+TreeMap+Comparator實(shí)現(xiàn)

 
 
 
 
  1. 1.  SortedMap sortedMap = new TreeMap(new Comparator() {
  2. 2.    @Override
  3. 3.    public int compare(K k1, K k2) {
  4. 4.      return k1.compareTo(k2);
  5. 5.    }
  6. 6.  });
  7. 7.  sortedMap.putAll(map);

實(shí)例代碼:

 
 
 
 
  1.   public class SortKeys2MapTest {
  2.       public static void main(String[] args) {
  3.           Map map = new HashMap<>();
  4.           map.put("2010", "jay");
  5.           map.put("1999", "whx");
  6.           map.put("3010", "huaxiao");
  7.   
  8.           SortedMap sortedMap = new TreeMap(new Comparator() {
  9.               @Override
  10.              public int compare(String k1, String k2) {
  11.                  return k1.compareTo(k2);
  12.              }
  13.          });
  14.          sortedMap.putAll(map);
  15.  
  16.          Iterator itr = sortedMap.entrySet().iterator();
  17.          while(itr.hasNext()) {
  18.              Map.Entry entry = (Map.Entry) itr.next();
  19.              // get key
  20.              String key = (String) entry.getKey();
  21.              // get value
  22.              String value = (String) entry.getValue();
  23.  
  24.              System.out.println("key:"+key+",value:"+value);
  25.          }
  26.      }
  27.  }

運(yùn)行結(jié)果:

 
 
 
 
  1.   key:1999,value:whx
  2.   key:2010,value:jay
  3.   key:3010,value:huaxiao

4、如何對(duì)Map的values進(jìn)行排序

 
 
 
 
  1.   List list = new ArrayList(map.entrySet());
  2.   Collections.sort(list, (Entry e1, Entry e2) ->{
  3.       return e1.getValue().compareTo(e2.getValue());
  4.     });

實(shí)例代碼:

 
 
 
 
  1.   public class SortValuesMapTest {
  2.       public static void main(String[] args) {
  3.           Map map = new HashMap<>();
  4.           map.put("2010", "jay");
  5.           map.put("1999", "whx");
  6.           map.put("3010", "huaxiao");
  7.   
  8.           List >list = new ArrayList<>(map.entrySet());
  9.           Collections.sort(list, (Map.Entry e1, Map.Entry e2)-> {
  10.                  return e1.getValue().toString().compareTo(e2.getValue().toString());
  11.              }
  12.          );
  13.  
  14.          for (Map.Entry entry : list) {
  15.              System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
  16.          }
  17.      }
  18.  }

運(yùn)行結(jié)果:

 
 
 
 
  1.   key:3010,value:huaxiao
  2.   key:2010,value:jay
  3.   key:1999,value:whx

5、如何初始化一個(gè)靜態(tài)/不可變的Map

初始化一個(gè)靜態(tài)不可變的map,單單static final+static代碼塊還是不行的,如下:

 
 
 
 
  1.   public class Test1 {
  2.       private static final Map map;
  3.       static {
  4.           map = new HashMap();
  5.           map.put(1, "one");
  6.           map.put(2, "two");
  7.       }
  8.       public static void main(String[] args) {
  9.           map.put(3, "three");
  10.          Iterator itr = map.entrySet().iterator();
  11.          while(itr.hasNext()) {
  12.              Map.Entry entry = (Map.Entry) itr.next();
  13.              // get key
  14.              Integer key = (Integer) entry.getKey();
  15.              // get value
  16.              String value = (String) entry.getValue();
  17.  
  18.              System.out.println("key:"+key+",value:"+value);
  19.          }
  20.      }
  21.  }

這里面,map繼續(xù)添加元素(3,"three"),發(fā)現(xiàn)是OK的,運(yùn)行結(jié)果如下:

 
 
 
 
  1.   key:1,value:one
  2.   key:2,value:two
  3.   key:3,value:three   

真正實(shí)現(xiàn)一個(gè)靜態(tài)不可變的map,需要Collections.unmodifiableMap,代碼如下:

 
 
 
 
  1.   public class Test2 {
  2.       private static final Map map;
  3.       static {
  4.           Map aMap = new HashMap<>();
  5.           aMap.put(1, "one");
  6.           aMap.put(2, "two");
  7.           map = Collections.unmodifiableMap(aMap);
  8.       }
  9.   
  10.      public static void main(String[] args) {
  11.          map.put(3, "3");
  12.          Iterator itr = map.entrySet().iterator();
  13.          while(itr.hasNext()) {
  14.              Map.Entry entry = (Map.Entry) itr.next();
  15.              // get key
  16.              Integer key = (Integer) entry.getKey();
  17.              // get value
  18.              String value = (String) entry.getValue();
  19.  
  20.             System.out.println("key:"+key+",value:"+value);
  21.          }
  22.      }
  23.  
  24.  }

運(yùn)行結(jié)果如下:

可以發(fā)現(xiàn),繼續(xù)往map添加元素是會(huì)報(bào)錯(cuò)的,實(shí)現(xiàn)真正不可變的map。

6、HashMap, TreeMap, and Hashtable,ConcurrentHashMap的區(qū)別

7、如何創(chuàng)建一個(gè)空map

如果map是不可變的,可以這樣創(chuàng)建:

 
 
 
 
  1.   Map map=Collections.emptyMap();
  2.   or
  3.   Map map=Collections.emptyMap();
  4.   //map1.put("1", "1"); 運(yùn)行出錯(cuò)

如果你希望你的空map可以添加元素的,可以這樣創(chuàng)建

 
 
 
 
  1. Map map = new HashMap();

8、有關(guān)于map的復(fù)制

有關(guān)于hashmap的復(fù)制,在日常開發(fā)中,使用也比較多。主要有 =,clone,putAll,但是他們都是淺復(fù)制,使用的時(shí)候注意啦,可以看一下以下例子:

例子一,使用=復(fù)制一個(gè)map:

 
 
 
 
  1.   public class CopyMapAssignTest {
  2.       public static void main(String[] args) {
  3.   
  4.           Map userMap = new HashMap<>();
  5.   
  6.           userMap.put(1, new User("jay", 26));
  7.           userMap.put(2, new User("fany", 25));
  8.   
  9.           //Shallow clone
  10.          Map clonedMap = userMap;
  11.  
  12.          //Same as userMap
  13.          System.out.println(clonedMap);
  14.  
  15.          System.out.println("\nChanges reflect in both maps \n");
  16.  
  17.          //Change a value is clonedMap
  18.          clonedMap.get(1).setName("test");
  19.  
  20.          //Verify content of both maps
  21.          System.out.println(userMap);
  22.          System.out.println(clonedMap);
  23.      }
  24.  }

運(yùn)行結(jié)果:

 
 
 
 
  1.   {1=User{name='jay', age=26}, 2=User{name='fany', age=25}}
  2.   
  3.   Changes reflect in both maps
  4.   
  5.   {1=User{name='test', age=26}, 2=User{name='fany', age=25}}
  6.   {1=User{name='test', age=26}, 2=User{name='fany', age=25}}

從運(yùn)行結(jié)果看出,對(duì)cloneMap修改,兩個(gè)map都改變了,所以=是淺復(fù)制。

例子二,使用hashmap的clone復(fù)制:

 
 
 
 
  1.   {
  2.       public static void main(String[] args) {
  3.           HashMap userMap = new HashMap<>();
  4.   
  5.           userMap.put(1, new User("jay", 26));
  6.           userMap.put(2, new User("fany", 25));
  7.   
  8.           //Shallow clone
  9.           HashMap clonedMap = (HashMap) userMap.clone();
  10.  
  11.          //Same as userMap
  12.          System.out.println(clonedMap);
  13.  
  14.          System.out.println("\nChanges reflect in both maps \n");
  15.  
  16.          //Change a value is clonedMap
  17.          clonedMap.get(1).setName("test");
  18.  
  19.          //Verify content of both maps
  20.          System.out.println(userMap);
  21.          System.out.println(clonedMap);
  22.      }
  23.  }

運(yùn)行結(jié)果:

 
 
 
 
  1.   {1=User{name='jay', age=26}, 2=User{name='fany', age=25}}
  2.   
  3.   Changes reflect in both maps
  4.   
  5.   {1=User{name='test', age=26}, 2=User{name='fany', age=25}}
  6.   {1=User{name='test', age=26}, 2=User{name='fany', age=25}}

從運(yùn)行結(jié)果看出,對(duì)cloneMap修改,兩個(gè)map都改變了,所以hashmap的clone也是淺復(fù)制。

例子三,通過(guò)putAll操作

 
 
 
 
  1.   public class CopyPutAllMapTest {
  2.       public static void main(String[] args) {
  3.           HashMap userMap = new HashMap<>();
  4.   
  5.           userMap.put(1, new User("jay", 26));
  6.           userMap.put(2, new User("fany", 25));
  7.   
  8.           //Shallow clone
  9.           HashMap clonedMap = new HashMap<>();
  10.          clonedMap.putAll(userMap);
  11.  
  12.          //Same as userMap
  13.          System.out.println(clonedMap);
  14.  
  15.          System.out.println("\nChanges reflect in both maps \n");
  16.  
  17.          //Change a value is clonedMap
  18.          clonedMap.get(1).setName("test");
  19.  
  20.          //Verify content of both maps
  21.          System.out.println(userMap);
  22.          System.out.println(clonedMap);
  23.      }
  24.  }

運(yùn)行結(jié)果:

 
 
 
 
  1.   {1=User{name='jay', age=26}, 2=User{name='fany', age=25}}
  2.   
  3.   Changes reflect in both maps
  4.   
  5.   {1=User{name='test', age=26}, 2=User{name='fany', age=25}}
  6.   {1=User{name='test', age=26}, 2=User{name='fany', age=25}}

從運(yùn)行結(jié)果看出,對(duì)cloneMap修改,兩個(gè)map都改變了,所以putAll還是淺復(fù)制。

那么,如何實(shí)現(xiàn)深度復(fù)制呢?

可以使用序列化實(shí)現(xiàn),如下為谷歌Gson序列化HashMap,實(shí)現(xiàn)深度復(fù)制的例子:

 
 
 
 
  1.   public class CopyDeepMapTest {
  2.   
  3.       public static void main(String[] args) {
  4.           HashMap userMap = new HashMap<>();
  5.   
  6.           userMap.put(1, new User("jay", 26));
  7.           userMap.put(2, new User("fany", 25));
  8.   
  9.           //Shallow clone
  10.          Gson gson = new Gson();
  11.          String jsonString = gson.toJson(userMap);
  12.  
  13.          Type type = new TypeToken>(){}.getType();
  14.          HashMap clonedMap = gson.fromJson(jsonString, type);
  15.  
  16.          //Same as userMap
  17.          System.out.println(clonedMap);
  18.  
  19.          System.out.println("\nChanges reflect in only one map \n");
  20.  
  21.          //Change a value is clonedMap
  22.          clonedMap.get(1).setName("test");
  23.  
  24.          //Verify content of both maps
  25.          System.out.println(userMap);
  26.          System.out.println(clonedMap);
  27.      }
  28.  }

運(yùn)行結(jié)果:

 
 
 
 
  1.   {1=User{name='jay', age=26}, 2=User{name='fany', age=25}}
  2.   
  3.   Changes reflect in only one map
  4.   
  5.   {1=User{name='jay', age=26}, 2=User{name='fany', age=25}}
  6.   {1=User{name='test', age=26}, 2=User{name='fany', age=25}}

從運(yùn)行結(jié)果看出,對(duì)cloneMap修改,userMap沒(méi)有被改變,所以是深度復(fù)制。


文章標(biāo)題:有關(guān)于JavaMap,應(yīng)該掌握的8個(gè)問(wèn)題
文章源于:http://www.dlmjj.cn/article/djocsgs.html