Remove the two kinds of ways set Map: keySet () and the entrySet () method Example

keySet()

Introduction:

 将map中所有的键存入到set集合,因为set具备迭代器。再通过set集合的迭代器取出键,通过map.get(key)获取对应的value.

The sample code

import java.util.*;
class MapDemo2 {
	public static void main(String[] args){
		Map<String,String> map = new HashMap<>();
		map.put("01","zhangsan1");
		map.put("02","zhangsan2");
		map.put("03","zhangsan3");
		map.put("04","zhangsan4");
		//先获取map集合的所有键的Set集合,keySet()
		Set<String> keySet = map.keySet();
		//有了set集合,可以获取其迭代器
		Iterator<String> it = keySet.iterator();
		while(it.hasNext()){
			String key = it.next();
			System.out.println("key:"+key);//key:01
											//key:02
											//key:03
											//key:04
			String value = map.get(key);
			System.out.println("key:"+key+"value:"+value); 

		}
	}
}

entrySet()

Introduction

Set <Map.Entry <k, v >> entrySet (): will be deposited into a collection of mapping relationship map to set collection. The data type of this relationship is: Map.Entry.
Map.Entry actually Entry is an internal interface Map of.

interface Map{
	public static interface Entry{
		public abstract  Object getValue();
		public abstract Object getKey()}
}
class HashMap implements Map{
	class hs implements Map.Entry{
		public Object getValue(){}
		public Object getKey(){}
	}
}

The sample code

import java.util.*;
class MapDemo2 {
	public static void main(String[] args){
		Map<String,String> map = new HashMap<>();
		map.put("01","zhangsan1");
		map.put("02","zhangsan2");
		map.put("03","zhangsan3");
		map.put("04","zhangsan4");
		//将map集合中的映射关系取出,存到Set
		Set<Map.Entry<String,String>> set = map.entrySet();
		//迭代器类型和set类型一致
		Iterator<Map.Entry<String,String>> it = set.iterator();
		while(it.hasNext()){
			Map.Entry<String,String> me = it.next();
			String key = me.getKey();
			String value = me.getValue();
			System.out.println("key:"+key+","+"value:"+value);
		/* 	key:01,value:zhangsan1
			key:02,value:zhangsan2
			key:03,value:zhangsan3
			key:04,value:zhangsan4 */
		}
	}
}
Released six original articles · won praise 0 · Views 102

Guess you like

Origin blog.csdn.net/qq_42487559/article/details/104114575