使用泛型迭代Map集合

2014-11-24 03:14:11 · 作者: · 浏览: 0

package com.bird.beanutils;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.Set;

import java.util.Map.Entry;

import org.junit.Test;

/**

* @use 使用泛型对Map进行迭代

* @author Bird

*

*/

public class DemoMap {

@Test

public void test1(){//对Map进行迭代

Map map = new LinkedHashMap();

map.put(1, "one");

map.put(2, "two");

map.put(3, "three");

map.put(4, "four");

map.put(5, "five");

map.put(7, "seven");

//传统EntrySet迭代

Set> set = map.entrySet();

Iterator> it = set.iterator();

while(it.hasNext()){

Map.Entry entry = it.next();

int key = entry.getKey();

String value = entry.getValue();

System.out.println("key" + " "+ key + "\n"+"value" + " "+ value);

}

}

@Test

public void test2(){//使用增强for循环

Map map = new LinkedHashMap();

map.put(1, "one");

map.put(2, "two");

map.put(3, "three");

map.put(4, "four");

map.put(5, "five");

map.put(7, "seven");

for(Map.Entry en : map.entrySet()){

int num = en.getKey();

String value = en.getValue();

System.out.println(num + "==" + value);

}

}

}

作者 a352193394