三、Java中级--6、Map
2018-05-07 本文已影响0人
cybeyond
集合和map
键值key不可以重复,但是值value可以重复。
- Map
- HashTable:底层存储结构是哈希表,键和值都不可以是null,已过时
- HashMap:底层是哈希表,键值都可以是null,不排序
- TreeMap:底层是二叉树,支持键排序
1、HashMap读取方式
-
(1)获得所有键的集合keyset
结构
package javastudy;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class MyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, String> cities=new HashMap<String,String>();
cities.put("010", "北京");
cities.put("021", "上海");
cities.put("022", "重庆");
cities.put("023", "天津");
Set<String> zips=cities.keySet();
Iterator<String> it=zips.iterator(); //遍历键
while(it.hasNext()){
String zip=it.next();
String cityName=cities.get(zip);
System.out.println(zip + ":"+cityName); //得到键的集合
}
}
}
执行结果
- (2)获得所有值的集合valueset
package javastudy;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class MyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, String> cities=new HashMap<String,String>();
cities.put("010", "北京");
cities.put("021", "上海");
cities.put("022", "重庆");
cities.put("023", "天津");
Collection<String>cityNames=cities.values();//cityNames存放所有城市的名称
Iterator<String> it=cityNames.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
执行结果
- (3)获得所有条目entryset(包括键和值)
package javastudy;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class MyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap<String, String> cities=new HashMap<String,String>();
cities.put("010", "北京");
cities.put("021", "上海");
cities.put("022", "重庆");
cities.put("023", "天津");
Set<Entry<String, String>> entries=cities.entrySet();
Iterator<Entry<String, String>> it=entries.iterator();
while(it.hasNext()){
Entry<String, String> entry=it.next(); //不能使用it.next指向两次
System.out.println(entry.getKey()+":"+entry.getValue());
}
}
}
执行结果