Map Summary of JAVA data structure

Source: Internet
Author: User
Tags set set

First look at the source code: Map is often used in the source code

/**     * Returns a {@code Set} containing all of the mappings in this {@code Map}. Each mapping are     * An instance of {@link map.entry}. As the {@code Set} is backed by this {@code Map}, * Changes in one would be reflected in the other     .     *     * @return A set of the mappings *     *    
1.EntrySet () is used to return a Set<map.entry<k,v>> object when traversing a Map. Map.entry<k,v> corresponds to a key-value pair in the map map. The map.entry<k,v> is then stored in the set object. The physical storage of the set object is also a map implementation, with the addition of an iterator function, 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 was reflected by the other. The {@code Set} does not     * support adding.     *     * @return A set of the keys.     *    /Public set<k> keySet ();

2.keySet ();deposits all the keys in the map into the set collection. Because set has iterators. All of the keys can be iterated out and then based on the Get method. Gets the value corresponding to each key. KeySet (): The key can only be taken after the iteration via get ()
/** * 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 was reflected by the other. The * {@code Collection} supports {@link collection#remove}, {@link Collection#removeall}, * {@link Collection#ret Ainall}, and {@link collection#clear} operations, * and it does not support {@link Collection#add} or {@link Collectio     N#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 Abstractcoll     Ection#contains} method wraps this {@code Map} ' s * {@link #containsValue} method. * <p> * The collection is created if this Method is called at first time and * returned in response to all subsequent calls. This method could return * different Collection when multiple calls to the This method, since it have no * synchronizatio     N performed.     * * @return A collection of the values contained in this map. */Public collection<v> values ();
3.values ():The method is to get all the values in the collection----no keys, no correspondence,
/**     * {@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> corresponds to a key-value pair in the map map. Used to traverse the map
Entry is used to iterate mapmap<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 ());}


The result of map traversal does not follow the order of put (K,V), and the sequence of values traversed is chaotic. Actually means:
HashMap are unordered, the order of TreeMap is the order of insertions eg:JAVA comes with a mapinterface is no sort feature. Even if you follow a certainsequential input, but the output is often random and uncomfortable for some special applications. In this time, you can use the TreeMap classIt's OK to convert it a bit. If you need the ability to sort, it's best to use the new map objectuse TreeMap. ButIf you sort the existing map by value, you need to convert it. 
eg
third, map understanding/*map Collection: Stores key-value pairs. To guarantee the uniqueness of the key.
Add to
Put (K key,v value)
Putall (map<? extends K,? extends v> m)
Delete
Clear ()
Remove (Object key)
Judge
Containsvalue (Object value)
ContainsKey (Object key)
IsEmpty ()
Get
Get (Object key)
Size ()
VALUES ()

MAP:
Hashtable (JDK1.0)
The underlying data structure is a hash table. The non-nullable key null value. Thread synchronization, low efficiency.
HashMap (JDK1.2)
The underlying data structure is a hash table. Null value is allowed to be stored in the null key. Different steps, high efficiency.
TreeMap
The underlying data structure is a two-fork tree. Thread is out of sync. Can be used to sort keys in the map collection.

Map and set and image, in fact, the set bottom is the use of the map collection.

Two ways to remove a map collection:
1 set<k> KeySet
Keyset all keys out and into the set set because the set has iterators.
You can use an iterator to remove all the keys and then get the corresponding values using the Get method
Principle: The map set is turned into a set set and then removed with an iterator.
2 set<map.entry<k,v>> EntrySet
EntrySet takes the mapping relationship (Map.entry type) out, deposits it into the set set, and then uses the
Getkey and GetValue in Map.entry get the keys and values.

In fact, entry is an internal interface of the map interface, the sub-interface
The map set has a mapping relationship and is the internal transaction of the map collection.
The data type that is stored in the map.entry is the mapping relationship.
Internal interface to add static modifiers
iv. Application of Map

1. Basic overview

set < map.entry < k v >>&NBSP; entryset () Span style= "Font-family:verdana" >  returns a set view of the mappings contained in this map.

Set < K > keySet() returns a set view of the keys contained in this map.

2. Efficiency analysis

For keyset is actually traversed 2 times, one is converted to iterator, one time from the HashMap to remove the value of key. And EntrySet just traversed the first time, he put the key and value in the entry, so soon.

3. Use Example

Map<string, string> maps = new hashmap<string, string> ();
Method one: With 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 ();
}
Method Two: jdk1.5 support, with EntrySet () and For-each loops ()
For (map.entry<string, string> m:maps.entryset ()) {
String key = M.getkey ();
String value= M.getvalue ();
}
Method Three: With Keyset ()
Iterator<string> it2 = Maps.keyset (). Iterator ();
while (It2.hasnext ()) {
String key = It2.next ();
String value= Maps.get (key);
}
Method Four: jdk1.5 support, with keyset () and For-each loops
For (String M:maps.keyset ()) {
String key = m;
String value= Maps.get (m);
}

The efficiency of the foreach and while is almost the same, whereas for is relatively slow. Can foreach replace for? Obviously not.
The internal principle of foreach is still Iterator, but it cannot be controlled like Iterator, and cannot be called iterator.remove (), nor can the subscript be used to easily access the element. Therefore, the loop of foreach is generally only suitable for the traversal of arrays, extracting data display, etc., and not suitable for adding complex operations such as deleting and using subscript.


Example:
Write value label <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 (); When the total number of//map mappings is greater than 20, a data int count = Sp.getall () is inserted at the end. 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{//iterator Iter.next (); Returns the next object of the iteration, 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)
Save HashMap all values 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 ();//high efficiency, you must use this way in the future! }

V. Ordering of MAP values

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

Map Summary of JAVA data structure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.