Java 集合 --- 如何遍历Map

Java 集合 --- 如何遍历Map

  • Map没有继承Collection接口
  • AbstractMap和AbstractCollection是平级关系
    在这里插入图片描述

Map的基本操作

package map;
import java.util.*;
/**
 * This program demonstrates the use of a map with key type String and value type Employee.
 * @version 1.12 2015-06-21
 * @author Cay Horstmann
 */
public class MapTest {
	public static void main(String[] args) {
		Map<String, Employee> staff = new HashMap<>();
		staff.put("144-25-5464", new Employee("Amy Lee"));
		staff.put("567-24-2546", new Employee("Harry Hacker"));
		staff.put("157-62-7935", new Employee("Gary Cooper"));
		staff.put("456-62-5527", new Employee("Francesca Cruz"));
		// print all entries
		System.out.println(staff);
		// remove an entry
		staff.remove("567-24-2546");
		// replace an entry
		staff.put("456-62-5527", new Employee("Francesca Miller"));
		// look up a value
		System.out.println(staff.get("157-62-7935"));
		// iterate through all entries
		staff.forEach((k, v) -> 
		System.out.println("key=" + k + ", value=" + v));
	}
}

如何遍历Map

the set of keys: 将所有的key作为一个set返回

Set<K> keySet()
Set<String> keys = map.keySet();
for (String key : keys) {
	do something with key
}

the collection of values (which is not a set): 将所有的value作为一个collection返回

Collection<V> values()
 Map<String,String> map=new HashMap<>();
        map.put("abc","123");
        map.put("efg","456");
        // 使用增强型for遍历循环Map集合
        Collection<String> values = map.values();
        for (String value : values) {
            System.out.println(value);
        }

the set of key/value pairs: 得到每一对key value pair

Set<Map.Entry<K, V>> entrySet()
for (Map.Entry<String, Employee> entry : staff.entrySet()) {
	String k = entry.getKey();
	Employee v = entry.getValue();
	do something with k, v
}

Type of HashMap

HashMap

  • Hash table based implementation of the Map interface
  • the default load factor (.75)
  • 有一个子类为LinkedHashMap, 元素按照加入顺序排序

TreeMap

  • A Red-Black tree based NavigableMap implementation.
  • 需要根据compareTo排序

EumerateHashMap

  • A specialized Map implementation for use with enum type keys.
  • All of the keys in an enum map must come from a single enum type that is specified

WeakHashMap

  • Hash table based implementation of the Map interface, with weak keys.
  • An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值