Learning map in Java (describes the usage of MAP and iterator in Java)

Source: Internet
Author: User

Q: If it is more appropriate to put data in map, it is more special to put data in other containers;

Map is a key-value correspondence. I know. I want to know under what circumstances can I use a key-value pair or an array or another two-dimensional container?

A: Java model.
I will give you some of my previous student representatives.
1 import java. util. Map;
2 Import java. util. hashmap;
3 Import java. util. hashset;
4 Import java. util. Set;
5 import java. util. iterator;
6
7
8 class hashmaptest {
9
10
11 public static void main (string [] ARGs ){
12
13 Map <string, string> map = new hashmap <string, string> ();

14 map. Put ("key1", "value1 ");
15 map. Put ("key2", "hashmap value2 ");
16
17 system. Out. println (Map. Get ("key2 "));
18
19 set <string> set = new hashset <string> ();

20 set. Add ("this is hashset test1 ");

21 set. Add ("this is hashset Test2 ");

22
23
24
25 iterator <string> iter = set. iterator ();

26 while (ITER. hasnext ()){
27 system. Out. println (ITER. Next ());

28}
29 for (string STR: Set ){
30 system. Out. println (STR );
31}
32
33
34}
35}

A: While map will automatically help you complete the search

A: similar to functions in mathematics, for example, y = f (x). Based on X, we can determine that the value of Y in map is

Map. Put ("X", "Y ");
Map. Get ("X") = y
It is actually a one-to-one ing relationship.

Key ------ Value

Each key corresponds to a value and the key knows the value.

2q: How does one obtain its value through the map key in Java?

A: object OBJ = new object ();
OBJ = map. Get ("key ");
Map is the object of map, and "key" is the value of key, which is generally a string.

A: Use the get (Object key) method to obtain

A: Map <string, string> maps = new hashmap <string, string> ();
// Obtain the set of keys
Set <string> keyset = maps. keyset ();
// Traverses the key set and obtains the value
For (string key: keyset ){
String value = maps. Get (key );
}

Related Article

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.