Java 数据结构之Map总结

首先查看源码: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>

4.Map.entry<K,V> 相当于Map映射中的一个键值对。用于遍历map所用

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());
		}

二、 Map遍历后的结果不会根据put(k,v)的先后,遍历的值顺序是乱的。其实指:

HashMap是无序的,TreeMap的顺序是插入的先后顺序Eg:JAVA 自带的Map接口是没有排序功能。即使你按照一定的顺序输入,但是输出结果也往往是随机的,对一些特殊的应用很不爽。这时候,可以使用TreeMap类进行转换一下就可以了。如果需要排序的功能,最好在new Map对象的时候,使用TreeMap. 但是如果对已经存在的Map进行按值排序,则需进行转换一下。
eg:

三、 Map理解

/*Map集合:存储键值对。要保证键的唯一性。

添加

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中存的是映射关系这种数据类型。

内部接口才能加静态修饰符

四、Map的运用

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 值排序

http://blog.sina.com.cn/s/blog_671565dd010151f8.html

时间: 2024-08-28 17:01:26

Java 数据结构之Map总结的相关文章

Java数据结构Map,List,Set及Queue相关的类图

闲来无事,把util包中相关的数据结构的类图及其关系画了一下,给大家分享一下. 总览图:  Map:  List and Set: Queue: Java数据结构Map,List,Set及Queue相关的类图

JAVA数据结构——Map之HashMap

JAVA数据结构--Map之HashMap 一.原型及简介 原型:public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable 简介:HashMap基于散列表实现的一个key-value数据结构,能够实现通过key值快速查找.HashMap继承自AbstractMap抽闲类,实现了Map接口. 二.数据结构原理介绍 如下图所示,HashMap

Java数据结构与算法之集合

线性表.链表.哈希表是常用的数据结构,在进行Java开发时,SDK已经为我们提供了一系列相应的类来实现基本的数据结构.这些类均在java.util包中. 一.Collection接口 Collection是最基本的集合接口,一个Collection代表一组Object.一些Collection允许相同元素而另一些不行.一些能排序而另一些不行.Java  SDK不提供直接继承自Collection的类,Java  SDK提供的类都是继承自Collection的"子接口"如List和Set

[Java] 多个Map的性能比较(TreeMap、HashMap、ConcurrentSkipListMap)

比较Java原生的 3种Map的效率. 1.  TreeMap 2.  HashMap 3.  ConcurrentSkipListMap 结果: 模拟150W以内海量数据的插入和查找,通过增加和查找两方面的性能测试,结果如下: Map类型 插入 查找(在100W数据量中)   10W 50W 100W 150W 0-1W 0-25W 0-50W Concurrent SkipListMap 62 ms 227 ms 433 ms 689ms 7 ms 80 ms 119 ms HashMap

Java中的Map List Set等集合类

Map List Set等集合类: 一.概述 在JAVA的util包中有两个所有集合的父接口Collection和Map,它们的父子关系: +Collection 这个接口extends自 --java.lang.Iterable接口 ├+List(接口 代表有序,可重复的集合.列表) │├ ArreyList     (Class 数组,随机访问,没有同步,线程不安全) │├ Vector        (Class  数组                   同步        线程全) │

java数据结构与算法之改良顺序表与双链表类似ArrayList和LinkedList(带Iterator迭代器与fast-fail机制)

转载请注明出处(请尊重原创!谢谢~): http://blog.csdn.net/javazejian/article/details/53073995 出自[zejian的博客] 关联文章: java数据结构与算法之顺序表与链表设计与实现分析 java数据结构与算法之双链表设计与实现 java数据结构与算法之改良顺序表与双链表类似ArrayList和LinkedList(带Iterator迭代器与fast-fail机制) ??这篇是数据结构与算法的第3篇,通过前两篇的介绍,对应顺序表和链表已有

java集合框架--Map集合

1.Map集合的概述 Map集合是将键映射到值的对象.一个映射不能包含重复的键.每个键最多只能映射到一个值. 2.Map接口和Collection接口的不同? Map集合存储元素是成对出现的,Collection集合存储元素是单独出现的. Map集合的键是唯一的,值是可重复的. Collection集合的子接口Set是唯一的,List是可重复的. Map集合的数据结构值针对键有效,和值无关,而Collection接口的数据结构是针对元素有效. 3.Map集合示例及功能 package cn; i

java并发容器(Map、List、BlockingQueue)

转发: 大海巨浪 Java库本身就有多种线程安全的容器和同步工具,其中同步容器包括两部分:一个是Vector和Hashtable.另外还有JDK1.2中加入的同步包装类,这些类都是由Collections.synchronizedXXX工厂方法.同步容器都是线程安全的,但是对于复合操作,缺有些缺点: ① 迭代:在查觉到容器在迭代开始以后被修改,会抛出一个未检查异常ConcurrentModificationException,为了避免这个异常,需要在迭代期间,持有一个容器锁.但是锁的缺点也很明显

JAVA中关于Map的九大问题

通常来说,Map是一个由键值对组成的数据结构,且在集合中每个键是唯一的.下面就以K和V来代表键和值,来说明一下java中关于Map的九大问题. 0.将Map转换为List类型 在java中Map接口提供了三种集合获取方式:Key set,,value set, and key-value set..它们都可以通过构造方法或者addAll()方法来转换为List类型.下面代码就说明了如何从Map中构造ArrayList: // key listList keyList = new ArrayLis