获取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(",");

}

}

}

代码运行后效果如下:

d166f5ad1e918e362f24ec7250d50027.png

原文:http://www.cnblogs.com/henuyuxiang/p/3868176.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值