首先查看源码:Map经常运用到的源码
/**
* Returns a {@code Set} containing all of the mappings in this {@code Map}. Each mapping is
* an instance of {@link Map.Entry}. As the {@code Set} is backed by this {@code Map},
* changes in one will be reflected in the other.
*
* @return a set of the mappings
*/
public Set<Map.Entry<K,V>> entrySet();
1.
entrySet() 是运用在遍历Map时,返回一个Set<Map.entry<K,V>>对象。Map.entry<K,V> 相当于Map映射中的一个键值对。然后将这个Map.entry<K,V>存放到Set对象里。Set对象的物理存储也是Map实现的,外加有迭代器功能, public Iterator<E> iterator();
/**
* Returns a set of the keys contained in this {@code Map}. The {@code Set} is backed by
* this {@code Map} so changes to one are reflected by the other. The {@code Set} does not
* support adding.
*
* @return a set of the keys.
*/
public Set<K> keySet();
2.keySet(); 将Map中所有的键存入到set集合中。因为set具备迭代器。所有可以迭代方式取出所有的键,再根据get方法。获取每一个键对应的值。 keySet():迭代后只能通过get()取key
/**
* Returns a {@code Collection} of the values contained in this {@code Map}. The {@code Collection}
* is backed by this {@code Map} so changes to one are reflected by the other. The
* {@code Collection} supports {@link Collection#remove}, {@link Collection#removeAll},
* {@link Collection#retainAll}, and {@link Collection#clear} operations,
* and it does not support {@link Collection#add} or {@link Collection#addAll} operations.
* <p>
* This method returns a {@code Collection} which is the subclass of
* {@link AbstractCollection}. The {@link AbstractCollection#iterator} method of this subclass returns a
* "wrapper object" over the iterator of this {@code Map}'s {@link #entrySet()}. The {@link AbstractCollection#size} method
* wraps this {@code Map}'s {@link #size} method and the {@link AbstractCollection#contains} method wraps this {@code Map}'s
* {@link #containsValue} method.
* <p>
* The collection is created when this method is called at first time and
* returned in response to all subsequent calls. This method may return
* different Collection when multiple calls to this method, since it has no
* synchronization performed.
*
* @return a collection of the values contained in this map.
*/
public Collection<V> values();
3.
values():
方法是获取集合中的所有的值----没有键,没有对应关系,
/**
* {@code Map.Entry} is a key/value mapping contained in a {@code Map}.
*/
public static interface Entry<K,V> {<span style="font-family: Tahoma, 'Microsoft Yahei', Simsun;">}</span>
entry用来迭代map Map<String, String> map = new HashMap<String, String>(); map.put("111", "aaa"); map.put("222", "bbb"); for (Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue()); }
HashMap是无序的,TreeMap的顺序是插入的先后顺序Eg:JAVA 自带的Map接口是没有排序功能。即使你按照一定的顺序输入,但是输出结果也往往是随机的,对一些特殊的应用很不爽。这时候,可以使用TreeMap类进行转换一下就可以了。如果需要排序的功能,最好在new Map对象的时候,使用TreeMap. 但是如果对已经存在的Map进行按值排序,则需进行转换一下。
eg:
添加
put(K key,V value)
putAll(Map<? extends K,? extends V> m)
删除
clear()
remove(Object key)
判断
containsValue(Object value)
containsKey(Object key)
isEmpty()
获取
get(Object key)
size()
values()
Map:
Hashtable(JDK1.0)
底层数据结构是哈希表。不可存null键null值。线程同步,效率低。
HashMap(JDK1.2)
底层数据结构是哈希表。允许存入null键null值。不同步,效率高。
TreeMap
底层数据结构是二叉树。线程不同步。可用于给map集合中的键排序。
Map和Set和像,其实Set底层就是使用了Map集合。
map集合的两种取出方式:
1 Set<K> keySet
keySet将所有键取出,存入Set集合,因为Set具备迭代器。
可以用迭代器取出所有键,然后用get方法获取对应值
原理:map集合转成Set集合,再用迭代器取出。
2 Set<Map.Entry<K,V>> entrySet
entrySet将映射关系(Map.Entry类型)取出,存入Set集合,然后用
Map.Entry中的getKey和getValue获取键和值。
其实Entry是Map接口的一个内部接口,即子接口
先有Map集合再有映射关系,是Map集合的内部事务
Map.Entry中存的是映射关系这种数据类型。
内部接口才能加静态修饰符
1、基本概述
Set<Map.Entry<K,V>> entrySet() 返回此映射中包含的映射关系的 set 视图。
Set<K> keySet() 返回此映射中包含的键的 set 视图。
2、效率分析
对于keySet其实是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对于的value。而entryset只是遍历了第一次,他把key和value都放到了entry中,所以就快了。
3、使用举例
Map<String, String> maps = new HashMap<String, String>();
//方法一: 用entrySet()
Iterator<Entry<String,String>> it = maps.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String,String> m = it.next();
String key = m.getKey();
String value= m.getValue();
}
// 方法二:jdk1.5支持,用entrySet()和For-Each循环()
for (Map.Entry<String, String> m : maps.entrySet()) {
String key = m.getKey();
String value= m.getValue();
}
// 方法三:用keySet()
Iterator<String> it2 = maps.keySet().iterator();
while (it2.hasNext()){
String key = it2.next();
String value= maps.get(key);
}
// 方法四:jdk1.5支持,用keySet()和For-Each循环
for(String m: maps.keySet()){
String key = m;
String value= maps.get(m);
}
foreach和while的效率几乎是差不多的,而for则相对较慢一些。foreach可以替代掉for吗?显然不是。
foreach的内部原理其实还是 Iterator,但它不能像Iterator一样可以人为的控制,而且也不能调用iterator.remove(),更不能使用下标来方便的访问元素。因此foreach这种循环一般只适合做数组的遍历,提取数据显示等,不适合用于增加删除和使用下标等复杂的操作。
//写入值 标签<string name="">value</string>
public static boolean saveSearchRecord(Context context,String key,String time){
SharedPreferences sp = context.getSharedPreferences("search_record", 0);
Editor e = sp.edit();
//map 映射的总数,大于20条时,末尾插入一条数据
int count = sp.getAll().size();
if(count <20){
e.putString(key, time);
//e.putInt("count", count+1);
}
else{
e.putString(key, time);
Iterator iter = sp.getAll().entrySet().iterator();
int cunIter = 1;
Boolean flag =true;
while (iter.hasNext()) {
if(cunIter < sp.getAll().size()){
cunIter++;
}else{
//迭代器iter.next(); 返回迭代的下一个对象,
Map.Entry entry = (Map.Entry) iter.next();
Log.v("Boolean", ""+iter.hasNext());
Log.v("key", (String) entry.getKey());
if(flag){
e.remove((String) entry.getKey());
flag= false;
}
}
}
}
return e.commit();
}
(2)
//存HashMap所有值
public static void saveHotNewsStatus(Context context,HashMap<String, String> map){
SharedPreferences sp = context
.getSharedPreferences("hotnews_status", 0);
Editor e = sp.edit();
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String key = (String) entry.getKey();
String val = (String) entry.getValue();
e.putString(key, val);
}
e.commit();
// 效率高,以后一定要使用此种方式!
}
五、 Map 值排序