进阶day04-Map集合的遍历(键找值)
This commit is contained in:
@@ -2,6 +2,7 @@ package com.inmind.map01;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/*
|
||||
Interface Map<K,V>
|
||||
@@ -19,6 +20,11 @@ Map的常用的实现类:
|
||||
- public boolean containKey(Object key):判断该集合中是否有此键。
|
||||
- public boolean containsValue(Object value):判断该集合中是否有此键。
|
||||
|
||||
|
||||
- public Set<K> keySet(): 获取Map集合中所有的键,存储到Set集合中。
|
||||
- public Set<Map.Entry<K,V>> entrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)。
|
||||
|
||||
|
||||
Map的特点:
|
||||
1.key是唯一不重复
|
||||
2.value是可以重复
|
||||
@@ -57,6 +63,14 @@ public class MapDemo01 {
|
||||
//- public boolean containsValue(Object value):判断该集合中是否有此键。
|
||||
System.out.println(map.containsValue("孙尚香"));
|
||||
System.out.println(map.containsValue("貂蝉"));
|
||||
System.out.println("-------------------获取双列集合的键------------------");
|
||||
//- public Set<K> keySet(): 获取Map集合中所有的键,存储到Set集合中。
|
||||
Set<String> keys = map.keySet();
|
||||
System.out.println(keys);
|
||||
|
||||
//- public Set<Map.Entry<K,V>> entrySet(): 获取到Map集合中所有的键值对对象的集合(Set集合)。
|
||||
System.out.println("----------------获取双列集合的键值对-----------------------");
|
||||
Set<Map.Entry<String, String>> entries = map.entrySet();
|
||||
System.out.println(entries);
|
||||
}
|
||||
}
|
||||
|
||||
41
javaSE-day04/src/com/inmind/map01/MapDemo02.java
Normal file
41
javaSE-day04/src/com/inmind/map01/MapDemo02.java
Normal file
@@ -0,0 +1,41 @@
|
||||
package com.inmind.map01;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/*
|
||||
3.Map集合的遍历(键找值)
|
||||
Map集合是没有索引,也不能获取迭代器,所以不能通过普通for循环,增强for循环直接遍历,只能间接遍历.
|
||||
|
||||
- public Set<K> keySet(): 获取Map集合中所有的键,存储到Set集合中。
|
||||
*/
|
||||
public class MapDemo02 {
|
||||
public static void main(String[] args) {
|
||||
//创建一个双列集合,K为String,V也为String
|
||||
Map<String, String> map = new HashMap<>();
|
||||
//添加一对数据(增加)
|
||||
map.put("刘备", "孙尚香");
|
||||
map.put("吕布", "貂蝉");
|
||||
map.put("董卓", "貂蝉");
|
||||
System.out.println(map);
|
||||
|
||||
//键找值遍历方式
|
||||
Set<String> keys = map.keySet();
|
||||
System.out.println("------------键找值-间接遍历--迭代器---方式一--------------");
|
||||
//间接遍历--迭代器---方式一
|
||||
Iterator<String> iterator = keys.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
String key = iterator.next();
|
||||
String value = map.get(key);
|
||||
System.out.println(key+"-"+value);
|
||||
}
|
||||
|
||||
System.out.println("------------键找值-间接遍历--foreach循环---方式二--------------");
|
||||
//间接遍历--foreach循环---方式二
|
||||
for (String key : keys) {
|
||||
String value = map.get(key);
|
||||
System.out.println(key+":"+value);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user