Map三種遍曆方式,map三種

來源:互聯網
上載者:User

Map三種遍曆方式,map三種

package decorator; import java.util.Collection; import java.util.HashMap;  import java.util.Map;  import java.util.Map.Entry;  import java.util.Set;  import org.junit.Before;  import org.junit.Test;  /** * 對於Map的三種方式遍曆 1.keySet() 2.values() 3.entrySet()  * 三種方式得到Set之後,都可以使用 foreach或者iterator, 不能使用for,因為資料結構決定的  *  * @author Administrator  *  */ public class MapCycle {            Map<Integer, String> map;                       // 準備好資料                      @Before                       public void testData() {                                 map = new HashMap<>();                                map.put(1, "淩一");                                map.put(2, "淩二");           map.put(3, "淩三");                                map.put(4, "淩四");                                map.put(5, "淩五");           }/** 測試三種方式,這三種方式最後都是遍曆Set,於是都可以使用 foreach或者Iterator **/              // 方式1: keySet()方法擷取到Set(key)                         @Test                          public void testFirst() {                                  Set<Integer> set = map.keySet();                                  for (Integer integer : set) {                                            System. out.println( map.get(integer));                                    }                        }              // 方式2:values()方法擷取到Collection(value)                          @Test                           public void testSecond() {                                   Collection<String> collection = map.values();                                   for (String string : collection) {                                            System. out.println(string);                                    }                        }                           // 方式3:entrySet()方法擷取到Set<Entry<key,value>>                          @Test               public void testThird() {                                    Set<Entry<Integer, String>> entries = map.entrySet();                                    for (Entry<Integer, String> entry : entries) {                                             System. out.println(entry.getValue());                                            }                               }                }

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.