Dark Horse Programmer-java Basics-Set Map

Source: Internet
Author: User

-----Java Training, Android training, iOS training,. NET training, look forward to communicating with you!

Map<k,v>

Map<k,v>:map is stored in the form of key-value pairs of elements, each of its elements are composed of keys and values of two elements, the key can not be duplicated, the value is repeatable, each key is unique point to a value.

Map system

Map

--|hashtable: The underlying is a hash table data structure that cannot be stored as a null key null value. The collection is thread-synchronized. Low efficiency, has been replaced by HashMap

--| HashMap: The underlying is a hash table data structure that allows NULL values and NULL keys, the thread is out of sync, the Hashtable is replaced with high efficiency

--| TREEMAP: The bottom layer is a two-fork tree data structure. Thread is out of sync. Can be used to sort keys in the map collection, with the same sort principle as TreeSet

Map features

A map holds a key-value pair, and the key is unique, and is the equivalent of re-assigning the current key value when re-adding to the existing key.

Map Basic methods

1. Add

V Put (K key, V value): Associates the specified value with the specified key in this map

void Putall (map<? extends K,? extends v> m): Copy all mappings from the specified mappings into this map

2. Delete

void Clear (): Remove all mappings from this map

V Remove (Object key): If there is a mapping relationship for a key, remove it from this mapping

3. Judging

Boolean Containsvalue (Object value): Returns True if this mapping maps one or more keys to the specified value.

Boolean ContainsKey (Object key): Returns TRUE if this map contains a mapping relationship for the specified key.

Boolean isEmpty (): Returns True if this mapping does not contain a key-value mapping relationship.

4. Get

V get (Object key): Returns the value mapped by the specified key, or null if the mapping does not contain a mapping relationship for the key.

int size (): Returns the number of key-value mapping relationships in this map.

VALUES (): Returns a Collection view of the values contained in this map.

EntrySet (): The mapping of keys and values is taken

KeySet (): Saves all the keys in the map to the set collection

Two ways to remove a map:

1, KeySet

Import Java.util.hashmap;import java.util.iterator;import Java.util.map;import Java.util.set;public class Demo {    public static void Main (string[] args) {        map<string, string> Map = new hashmap<string, string> ();        Study number, name        map.put ("Lisi1");        Map.put ("Lisi2");        Map.put ("Lisi3");        Map.put ("" "," Lisi4 ");        set<string> set = Map.keyset ();//Gets all the keys of the map collection into the set set;        Iterator<string> it = Set.iterator ();        while (It.hasnext ()) {            String key = It.next ();            String value = Map.get (key);//A key can get its corresponding value through the Get method of the map collection.            System.out.println ("School Number:" +key + "...) Name: "+ Value";}}}    

2, Enteyset

Import Java.util.hashmap;import java.util.iterator;import Java.util.map;import Java.util.set;public class Demo {    public static void Main (string[] args) {        map<string, string> Map = new hashmap<string, string> ();        Study number, name        map.put ("Lisi1");        Map.put ("Lisi2");        Map.put ("Lisi3");        Map.put ("" "," Lisi4 ");        Set<map.entry<string,string>> Entryset=map.entryset ();        Iterator<map.entry<string,string>> it=entryset.iterator ();        while (It.hasnext ()) {            map.entry<string, string> entry=it.next ();            String Key=entry.getkey ();            String Value=entry.getvalue ();            System.out.println ("School Number:" +key + "...) Name: "+ Value";}}}    

Hashtable

Data structure is a hash table, cannot store null key null value, thread synchronization, security, low efficiency.

HashMap

Data structure is hash table, can store null key null value, thread is out of sync, high efficiency

TreeMap

The data structure is a two-fork tree (red-black tree), which can store null key null values, threads are out of sync and high efficiency.

Comprehensive case

(a) HashMap

Package Set;/*map comprehensive exercise A map collection is used because of the mapping relationship. "Yureban" Student ("Zhangsan"); Yureban "Student" ("Lisi"); " "Jiuyeban" "Wangwu"; " Jiuyeban "" Zhaoliu "; a school has multiple classrooms. Every classroom has a name.    */import java.util.*;class student{private String ID;    private String name;        Student (String id,string name) {this.id = ID;    THIS.name = name;    } public String toString () {return id+ ":::" +name; }}public class mapdemo3{public static void demo () {hashmap<string,list<student>> CZBK = new Ha        Shmap<string,list<student>> ();        list<student> Reyu = new arraylist<student> ();        list<student> Jiuye = new arraylist<student> ();        Czbk.put ("Yureban", Reyu);        Czbk.put ("Jiuyeban", Jiuye);        Reyu.add ("Student", "Zhagnsa");        Reyu.add ("Student", "Wangwu");        Jiuye.add ("Student", "Zhouqi");        Jiuye.add ("Student", "Zhaoli"); Iterator<string> it =Czbk.keyset (). iterator ();            while (It.hasnext ()) {String roomname = It.next ();                        list<student> = Czbk.get (roomname);            System.out.println (Roomname);        Getinfos (guest);        }} public static void Getinfos (List<student> List) {iterator<student> it = list.iterator ();            while (It.hasnext ()) {Student s = it.next ();        System.out.println (s);    }} public static void Main (string[] args) {demo (); }}

Two

/* Each student has a corresponding place of attribution. Student student, address string. Student attributes: Name, age. Note: The same name and age are regarded as the same student. Ensure the uniqueness of students. 1, describe the student. 2, define the map container. Use the student as the key, the address as the value. Deposit. 3, gets the elements in the map collection.    */import Java.util.*;class Student implements comparable<student>{private String name;    private int age;        Student (String Name,int age) {this.name = name;    This.age = age;        } public int CompareTo (Student s) {int num = new Integer (this.age). CompareTo (New Integer (s.age));        if (num==0) return This.name.compareTo (S.name);    return num;    } public int hashcode () {return name.hashcode () +age*34; } public boolean equals (Object obj) {if (! (        obj instanceof Student)) throw new ClassCastException ("Type Mismatch");        Student s = (Student) obj;            Return This.name.equals (s.name) && this.age==s.age;    } public String GetName () {return name;    } public int Getage () {return age; } public String toString () {return name+ ":" +age; }}class maptest{public static void Main (string[] args) {hashmap<student,string> HM = new Hashmap&lt ;        Student,string> ();        Hm.put (New Student ("Lisi1"), "Beijing");        Hm.put (New Student ("Lisi1"), "Tianjin");        Hm.put (New Student ("Lisi2"), "Shanghai");        Hm.put (New Student ("Lisi3"), "Nanjing");        Hm.put (New Student ("Lisi4"), "Wuhan");        The first method of removal keySet set<student> KeySet = Hm.keyset ();        Iterator<student> it = Keyset.iterator ();            while (It.hasnext ()) {Student Stu = It.next ();            String addr = Hm.get (stu); System.out.println (stu+ "..."        +ADDR);        }//second method of removal entryset set<map.entry<student,string>> entryset = Hm.entryset ();                Iterator<map.entry<student,string>> iter = Entryset.iterator ();    while (Iter.hasnext ()) {map.entry<student,string> me = Iter.next ();        Student stu = Me.getkey ();            String addr = Me.getvalue ();        System.out.println (stu+ "..." +addr); }    }}

Three

/* Exercise: "SDFGZXCVASDFXCVDF" gets the number of occurrences of the letter in the string. Want to print results: A (1) C (2) ..... The results show that each letter has a corresponding number of times. Indicates that there are mappings between letters and times. Note that when a mapping relationship is found, you can select the Map collection. Because the map collection is stored as a mapping relationship. What about using the map collection? When there is a mapping between the data, you need to think of the map collection first. Idea: 1, converts a string into a character array. Because you want to operate on every single letter. 2, define a map collection, because the letters of the printed results are in order, so use the TreeMap collection.    3. Iterate through the character array.    Use each letter as a key to check the map collection.    If NULL is returned, the letter and 1 are stored in the map collection.    If the return is not NULL, it indicates that the letter already exists in the map collection and has a corresponding number of times. Then get the number of times and self-increment. , and then deposit the letter and the number of times since the increment into the map collection. Overrides the value that corresponds to the calling principle key. 4, returns the data in the map collection into the specified string form. */import java.util.*;class maptest3{public static void Main (string[] args) {String s= charcount ("AK+ABAF1        C,dckaabc-defa ");    System.out.println (s);        public static string CharCount (String str) {char[] chs = Str.tochararray ();                treemap<character,integer> TM = new treemap<character,integer> ();        int count = 0; for (int x=0; x<chs.length; x + +) {if (!) ( Chs[x]>= ' A ' && chs[x]<= ' z ' | |        chs[x]>= ' A ' && chs[x]<= ' Z ')) continue;    Integer value = Tm.get (Chs[x]);            if (value!=null) count = value;            count++;            Tm.put (Chs[x],count);//store characters and numbers directly into the collection, why, because they are automatically boxed.            Count = 0;            /* if (value==null) {tm.put (chs[x],1);                } else {value = value + 1;            Tm.put (Chs[x],value);        } */}//SYSTEM.OUT.PRINTLN (tm);        StringBuilder sb = new StringBuilder ();        set<map.entry<character,integer>> EntrySet = Tm.entryset ();        Iterator<map.entry<character,integer>> it = Entryset.iterator ();            while (It.hasnext ()) {map.entry<character,integer> me = It.next ();            Character ch = me.getkey ();            Integer value = Me.getvalue ();        Sb.append (ch+ "(" +value+ ")");    } return sb.tostring (); }}

Dark Horse Programmer-java Basics-Set Map

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.