栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

获取map中的一个value值以及遍历map获得map里所有key、value的值

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

}

}

}

代码运行后效果如下:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/845541.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号