獲取map中的一個value值以及遍歷map獲得map里所有key、value的值


前言:

1.聲明一個map: Map map = new HashMap();
2.向map中放值,注意:map是key-value的形式存放的.如:

map.put(”sa”,”dd”);

3.從map中取值:String str = map.get(”sa”).toString();結果是:str = ”dd”;
4.遍歷一個map,從中取得key 和value
Map map = new HashMap() ;

Iterator it = map.entrySet().iterator() ;
while (it.hasNext())
{
Map.Entry entry = (Map.Entry) it.next() ;
Object key = entry.getKey() ;
Object value = entry.getValue() ;
}

Java代碼如下:

package Test01;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Test03 {
	public static void main(String[] args){
		a();
		b();
	}
	@SuppressWarnings("unchecked")
	public static void a(){
		@SuppressWarnings("rawtypes")
		Map map = new HashMap();
		map.put("1","aa");
		map.put("2","bb");
		map.put("3","cc");
		map.put("4","dd");
		map.put("5","ee");
		map.put("6","ff");
		map.put("7","gg");
		
		String str = map.get("5").toString();
		System.out.println(str);		
	}
	
	@SuppressWarnings("unchecked")
	public static void b(){
		@SuppressWarnings("rawtypes")
		Map map = new HashMap();
		map.put("1","aa");
		map.put("2","bb");
		map.put("3","cc");
		map.put("4","dd");
		map.put("5","ee");
		map.put("6","ff");
		map.put("7","gg");
		@SuppressWarnings("rawtypes")
		Iterator it = map.entrySet().iterator() ;
		while (it.hasNext())
		{
		@SuppressWarnings("rawtypes")
		Map.Entry entry = (Map.Entry) it.next() ;
		Object key = entry.getKey() ;
		Object value = entry.getValue() ;
		System.out.print("["+key+"、");
		System.out.print(value+"]");
		System.out.print(",");
		}
	}
}

 

代碼運行后效果如下:

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM