Map集合遍历总结(Java: 集合与泛型(四))

4 篇文章 0 订阅
2 篇文章 0 订阅

一丶获取集合中所有key-value的key组成的Set集合后进行遍历:

1.加强for循环:

public class Main {
	public static void main(String[] args) {
		Map<String, Integer> scores = new HashMap<String, Integer>();
		scores.put("Tom", 91);
		scores.put("Jim", 89);
		scores.put("Jack", 95);
		Set<String> names = scores.keySet();
		for(String key : names) {
			System.out.println(key);
		}//换行依次输出"Tom","Jim","Jack"
	}
}

不足:该方法只能遍历Map集合的key值.

2.利用迭代器进行遍历:

public class Main {
	public static void main(String[] args) {
		Map<String, Integer> scores = new HashMap<String, Integer>();
		scores.put("Tom", 91);
		scores.put("Jim", 89);
		scores.put("Jack", 95);
		Set<String> names = scores.keySet();
		Iterator iterator = names.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}//换行依次输出"Tom","Jim","Jack"
	}
}

二丶将HashMap集合中key-value用Entry对象包含后进行遍历

1.加强for循环:

public class Main {
	public static void main(String[] args) {
		Map<String, Integer> scores = new HashMap<String, Integer>();
		scores.put("Tom", 91);
		scores.put("Jim", 89);
		scores.put("Jack", 95);
		Set<Entry<String, Integer>> entries = scores.entrySet();
		for(Entry content : entries) {
			System.out.println(content);
		}//换行输出为:Tom=91 Jack=95 Jim=89
	}
}

2.利用迭代器进行遍历:

public class Main {
	public static void main(String[] args) {
		Map<String, Integer> scores = new HashMap<String, Integer>();
		scores.put("Tom", 91);
		scores.put("Jim", 89);
		scores.put("Jack", 95);
		Set<Entry<String, Integer>> entries = scores.entrySet();
		Iterator<Entry<String, Integer>> iterator = entries.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}//换行输出为:Tom=91 Jack=95 Jim=89
	}
}

注:上述代码中均省略了引包代码,eclipse用户可利用快捷键CTRL+shift+o进行快速引包操作.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值