1、遍历map集合需要用到的方法
public set<k> keyset() :将Map所有的key封装到一个set的集合
public v get(object key) :根据key获取Map中对应的value值
public set <Map,entry<k,v>> entryset():获取所有的键值对对象集合
public collection<v> values():将map中所有的value封装到一个collection体系的集合
2、 遍历map集合有几种方式
第一种:根据键找值方式遍历
第二种:获取所有的键值对对象集合,通过迭代器遍历
第三种:获取所有的键值对对象集合,通过增强for遍历
第四种:通过map集合中的values方法,拿到所有的值

import java.util.*;
public class MapDemo {
public static void main(String[] args) {
Map<String,String> hm=new HashMap<String, String>();
hm.put("sp001","手机" );
hm.put("sp002","平板" );
hm.put("sp003","鼠标" );
/*第一种:键值对方式遍历map集合
* pulic v get(object key) 根据key获取map中对应的value
* public set<k> keyset() 将map中所有的key封装到一个set集合中
* */
Set<String> set = hm.keySet();
for (String key : set) {
String value = hm.get(key);
System.out.println("商品的编号:"+key+",商品的名称:"+value);
}
System.out.println("--------------------");
/*第二种:获取键值对对象的集合,迭代器遍历集合获取键和值
* pulic set<map,entry<k,v>> entryset():获取所有键值对对象集合
* */
Set<Map.Entry<String, String>> entrySet = hm.entrySet();
Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println("商品的编号:"+key+",商品的名称:"+value);
}
/*
* 第三种遍历:获取键值对对象集合,增强for遍历集合获取键和值
* pulic set<map,entry<k,v>> entryset();
*
* */
System.out.println("-----------");
Set<Map.Entry<String, String>> entrySet1 = hm.entrySet();
for (Map.Entry<String, String> entry : entrySet1) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("商品的编号:"+key+",商品的名称:"+value);
}
/*
* 第四种遍历:map集合中的values方法
* */
Collection<String> values = hm.values();
for (String value : values) {
System.out.println("商品的名称:"+value);
}
}
}
3、map的实现类有哪些
A:TreeMap:使用二叉树进行存储key-value;
B: HashTable:版本较低,线程安全,效率低,不能使用null作为key和value,对应的hashmap线程不安全,但是效率高
C:LinkedHashMap:底层使用链表来维护key-value的次序
D:properties:也可以key-value作为键值对存储信息
本文详细介绍了Java中Map集合的四种遍历方法,包括根据键找值、获取键值对对象集合的迭代器遍历、增强for遍历及通过values方法获取所有值。同时,还概述了Map的主要实现类,如TreeMap、HashTable、HashMap、LinkedHashMap和Properties,及其各自的特点和适用场景。
1891

被折叠的 条评论
为什么被折叠?



