Java Learning Map Interface

Source: Internet
Author: User

The Map collection and the collection collection are completely separate

A collection in collection , where elements exist in isolation, storing a single- column collection in a way that stores elements in a collection in one element

A set in a map in which elements are paired , each element consists of a key and a value , and the corresponding value is found by the key. double-column collection

A collection in map cannot contain duplicate keys, values can be repeated, and each key can only correspond to one value

Common collections in Map are HashMap collections, Linkedhashmap collections

HashMap Collection

hashmap<k,v> : The hash table structure in which the data is stored, the access order of the elements cannot be guaranteed. the hashcode () method, Equals () method, which requires overriding the key, is required to ensure that the key is unique and non-repeatable.

Linkedhashmap Collection

linkedhashmap<k,v> : HashMap has sub-class Linkedhashmap, which stores data using the hash table structure + linked list structure. The structure of the linked list ensures that the access order of the elements is consistent; the Hashcode () method, the Equals () method, which can guarantee the uniqueness and non-repetition of keys through the hash table structure.

Note : The collection in the map interface has two generic variable <k,v>, which, when used, assigns a data type to two generic variables. The data type of the two generic variables <K,V> can be the same or different.

Common methods in Map interfaces

Package Com.oracle.demo1;import Java.util.hashmap;import Java.util.iterator;import java.util.map;import Java.util.map.entry;import Java.util.set;public class Mapdemo {public static void main (string[] args) {put (); System.out.println ("======================"); get (); System.out.println ("======================");d elete (); System.out.println ("======================"); Bianli (); System.out.println ("======================"); Bianli2 ();} /* add element V put to the collection (K key, V value) associates the specified value with the specified key in this map (optional operation). * If the collection does not have this key before it is stored, then returns NULL if the key is stored in the previous collection, then the value corresponding to the key is replaced, and the value corresponding to the */public static void put () {Map<integer is returned. string> m = new Hashmap<integer, string> (); String V1 = m.put (1, "Zhang San"); String v2 = m.put (2, "John Doe"); String v3 = m.put (3, "Harry"); String v4 = m.put (3, "Zhao Liu"); System.out.println (v1 + "---" + v2 + "---" + v4); System.out.println (m);} /* * Gets the value of the specified key in the map collection V get (Object key) returns the value mapped by the specified key, or null if the mapping does not contain a mapping for the key. */public static void Get () {map<integer, string> m = new Hashmap<integer, String> (); m.put (1, "Zhang San"); M.put (2, "John Doe"); M.put (3, "Harry"); String v = m.get (1); System.out.println (v);} /* Delete element V remove (Object key) If there is a mapping relationship for a key, it is removed from this mapping (optional action).
* 1, delete the incoming key and the corresponding value * 2, return the value that corresponds to the key you want to delete */public static void Delete () {Map<integer, string> m = new Hashmap<in Teger, String> (), M.put (1, "Zhang San"), M.put (2, "John Doe"), M.put (3, "Harry"); System.out.println (m); String v = m.remove (3); System.out.println (v); System.out.println (m);} /* * Traverse the Map collection key to find the value * 1, get all of your keys corresponding to the set set * 2, traverse your set set, then take the corresponding values value */public static void Bianli () {Map<integer, string& Gt m = new Hashmap<integer, string> (), M.put (1, "Zhang San"), M.put (2, "John Doe"), M.put (3, "Harry");//1, Get set set with keys//Set<integer > S=m.keyset ();//2, enhanced for traversal set set for (Integer I:m.keyset ()) {//get key int key = i;//Get value String values = M.get (key); SYSTEM.OUT.PRINTLN (key + "= = =" + values);} System.out.println ("================");//Iterator traversal set<integer> set = M.keyset ();iterator<integer> it = Set.iterator (); while (It.hasnext ()) {int key = It.next (); String values = M.get (key); SYSTEM.OUT.PRINTLN (key + "= = =" + values);}} /* * to traverse the map through a mapping relationship gets all the key-value pairs (Entry) objects in the Map collection, returned as a set collection. * By enhancing for loop and iteratorTraverse the set collection to get the data in the Map */public static void Bianli2 () {map<integer, string> m = new Hashmap<integer, string> (); M.pu T (1, "Zhang San"); M.put (2, "John Doe"); M.put (3, "Harry");//1, first get Set set//Set<map.entry<integer, string>> set = M.entryset () ;//Iterator<map.entry<integer, string>> it = Set.iterator ();//while (It.hasnext ()) {//map.entry< Integer, string> map = It.next ();//int k = Map.getkey ();//String v = map.getvalue ();//System.out.println (k + "====== "+ V");//}//Enhanced for traversal set for (Map.entry<integer, string> map:m.entryset ()) {int k = Map.getkey (); String v = map.getvalue (); System.out.println (k + "======" + V);}}}

How to find values in the map key

key to find the value : that is, by the key in the element, the value corresponding to the key is obtained

Operating Procedures and illustrations:

1. Gets all the keys in the map collection, because the keys are unique , so return a set set to store all the keys

2. Iterate through the set of keys to get each key

3. According to the key, get the value corresponding to the key

Entry Key-value pairs

Entry encapsulates the corresponding relationship of a key-value pair into an object. That is, the key-value pair object, so that when we traverse the map collection, we can get the corresponding key and corresponding value from each key-value pair (Entry) object.

Entry is a static internal nested interface provided in the map interface that can be called directly with the class name

GetKey () Method: Gets the key in the entry object

GetValue () Method: Gets the value in the entry object

EntrySet () Method: Used to return all key-value pairs (Entry) objects in the Map collection, returned as a set set

How key-value pairs are traversed in map

Key-value pairs: that is, through each key-value pair in the collection (Entry) object that gets the keys and values in a key-value pair (Entry) object.

Operating Procedures and illustrations:

1. Gets all the key-value pairs (Entry) objects in the Map collection, returned as a set collection.

2. Traverse the set set containing the key-value pairs (Entry) object to get each key-value pair (Entry) object

3. Gets the key and value in the Entry object by using a key-value pair (Entry) object.

HashMap storing custom type key values

Package Com.oracle.demo1;public class Person {string Name;int age;public string GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public person () {}public person (String name, int age) {super (); this.name = Name;this.age = age;} @Overridepublic String toString () {return name + "----" + age;} @Overridepublic int hashcode () {final int prime = 31;int result = 1;result = Prime * result + Age;result = Prime * result + ((name = = null)? 0:name.hashcode ()); return result;} @Overridepublic boolean equals (Object obj) {if (this = = obj) return true;if (obj = = null) return False;if (GetClass ()! = obj . GetClass ()) return false; person other = (person) obj;if (age! = other.age) return false;if (name = = null) {if (other.name! = null) return false;} Els E if (!name.equals (other.name)) return False;return true;}}

  

package Com.oracle.demo1;import Java.util.hashmap;public class HashMapDemo { public static void Main (string[] args) {key (); System.out.println ("============="); values ();} public static void Key () {///when a custom class is used as a key, because the class does not override the Hashcode and Equals method//So the input data is stored in spite of duplicate data, the key cannot be duplicated due to the specification of key-value pairs in Java,// So you need to override the hashcode and Equals methods in the custom class Hashmap<person, string> hs = new Hashmap<person, string> (), Hs.put (new person ("Zhang San"), "Java"), Hs.put ("John Doe", "PHP"), Hs.put (New person ("Zhang San"), "Python"), Hs.put (The new person ("Harry", ), "Java"); SYSTEM.OUT.PRINTLN (HS);} public static void values () {//string class as a key, because the string overrides the Hashcode and equals methods//So when the input key has duplicate data, it is automatically recognized, guaranteeing the uniqueness of the key hashmap< String, person> hs = new hashmap<string, person> (), Hs.put ("Java", New person ("Zhang San"), Hs.put ("PHP", new person ("John Doe", 34)); Hs.put ("Python", New Person ("Zhang San"), Hs.put ("Java", New Person ("Harry", 18)); SYSTEM.OUT.PRINTLN (HS);}} 

  when giving When storing a custom object in HashMap, if the custom object exists as a key, it is necessary to ensure that the object is unique and that the hashcode and equals methods of the object must be replicated

If you want to ensure that the keys stored in the map are in the same order as they are taken out, you can use the Linkedhashmap collection to store them.

Package Com.oracle.demo1;import Java.util.hashmap;import Java.util.linkedhashmap;public class LinkedHashMapDemo { Public     static void Main (string[] args) {     //linkedhashmap is ordered, that is, how to save     linkedhashmap<string,string > Lhm=new linkedhashmap<string,string> ();     Lhm.put ("abc", "Zhang San");     Lhm.put ("Java", "John Doe");     Lhm.put ("AAC", "Harry");     Lhm.put ("GDR", "Zhang San");         System.out.println (LHM);       HashMap is not orderly, not necessarily how to save how to take     hashmap<string,string> hm=new hashmap<string,string> ();     Hm.put ("abc", "Zhang San");     Hm.put ("Java", "John Doe");     Hm.put ("AAC", "Harry");     Hm.put ("GDR", "Zhang San");         SYSTEM.OUT.PRINTLN (HM);}}

Static Import

In the course of the guide we can import the static part directly, so that the static members of a class can be used directly. Static import often occurs in the source code.

Static import Format:

Import static XXX.   YYY; YYY can be used directly after import.

Package Com.oracle.demo2;import static Java.lang.system.out;import static Java.util.arrays.sort;public class Ststicdemo {public static void main (string[] args) {out.println ("This is a static import"), int[] arr = {2, 4, 6, 3, 6, 1, 8};sort (arr); fo R (int i:arr) {out.println (i);}}}

Variable parameters

in the After JDK1.5, if we define a method that needs to accept multiple arguments, and multiple parameter types are consistent

Package Com.oracle.demo2;public class Demo {public static void main (string[] args) {System.out.println (Add (1, 2, 3, 4, 5, 6, 7, 8, 9, 10));} Variable parameter parameter types are the same, but the number of parameters is variable//int ... A is actually an array//NOTE: 1, if you need to pass in a parameter list of more than one type, the mutable list must be put to the last//       such as: public static void Add (String Str,int. a) {}         //    2, only one variable parameter in a parameter list public static int Add (int ... a) {int sum = 0;for (int i = 0; i < a.length ; i++) {sum = sum + a[i];} return sum;} public static int Add (int a, int b) {//return a + b;//}}

Collections Collection Tool Class

Common methods

Package Com.oracle.demo2;import Java.util.arraylist;import Java.util.collections;import Java.util.List;public class Collectionsdemo {public static void main (string[] args) {list<integer> List = new arraylist<integer> (); List.add (1); List.add (4); List.add (2); List.add (3); List.add (9); List.add (7); SYSTEM.OUT.PRINTLN (list); System.out.println ("=====================");//The Order of the elements in the collection is scrambled//the method return value is static, so call the method directly with the class name// This method is limited to list collection collections.shuffle (list); SYSTEM.OUT.PRINTLN (list); System.out.println ("====================="); Collections.sort (list); SYSTEM.OUT.PRINTLN (list);}}

Collection nesting

the so-called set nesting is the collection content is also a collection, such as Collection sets nested, collection sets and map sets are nested with each other, and map collections are nested.

1, ArrayList nested ArrayList

arraylist< arraylist<string> >

collection< arraylist<integer> >

2. Map Nesting ArrayList

Hashmap<string, arraylist<person>>

arraylist< hashmap<string, string>>

3. Map Set Nesting

Hashmap<string, hashmap<string,string>>

Hashmap<string, hashmap<person,string>>

Package Com.oracle.demo2;import Java.util.hashmap;import java.util.map;import java.util.set;//collection map nested map Save and fetch public class Mapqiantao {public static void main (string[] args) {//Collection nested hashmap<string, Hashmap<integer, String >> map = new hashmap<string, Hashmap<integer, string>> (); Hashmap<integer, string> m1 = new Hashmap<integer, string> (), M1.put (1, "Zhang San"), M1.put (2, "John Doe"); Map.put (" Java01 ", M1); Hashmap<integer, string> m2 = new Hashmap<integer, string> (); M2.put (1, "Little Red"); M2.put (2, "Xiao Li"); Map.put (" Java03 ", m2); SYSTEM.OUT.PRINTLN (map);//Get Element (KeySet) Get set set set<string> set = Map.keyset ();//Traverse Set set for (String str:set) {//Won Take class name String key = str;//Get class Maphashmap<integer, string> value = Map.get (key);            System.out.println (key+ "-------" +value); Get keysetset<integer> Set2=value.keyset () in class map,//Traversal study number for (int i:set2) {//Get student number int key2=i;// Get the student number corresponding to the name string Value2=value.get (Key2); System.out.println (key+ "----" +key2+ "-----" +value2);}} System.out.println ("==========================");//Get Elements with entryset//Get mapping relationship setset<map.entry<string, HashMap <integer, string>>> Set2=map.entryset (); for (map.entry<string, Hashmap<integer, String>> A:        Set2) {//Get class name String K1=a.getkey (); Get class Maphashmap<integer, string> V1=a.getvalue ();//Get Class map mapping relationship Set<map.entry<integer, string>> S3=v1.entryset ();//traverse for (Map.entry<integer, string> b:s3) {//Get student number int k2=b.getkey ();//Get Student name String v2= B.getvalue (); System.out.println (k1+ "--" +k2+ "-------" +v2);}}}

  

Java Learning Map Interface

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.