Common methods for Java map classes

Source: Internet
Author: User
Tags comparable delete key map class set set

About common methods in the map collection:

void Clear (); Clear Map

Boolean ContainsKey (Object key); Determine if the map contains such a key

Boolean Containsvalue (Object value); Determine if the map contains such value

Set<map.entry<k,v>> EntrySet (); Returns a set view of the mappings contained in this map

Object get (object key); Get value from key

Boolean isEmpty (); Determines whether the collection is empty

Set KeySet (); Get all the keys in the map

Object put (object Key,object value); To add a key-value pair to the collection

Object remove (object key); Delete the key value by key

int size (); Get the number of key-value pairs in a map

Set KeySet (); Get all the keys in the map

Collection values (); Gets all the value in the Map collection

Note: The elements stored in the key section of the map collection need to be overridden both by the hashcode and the Equals method (as mentioned in the previous hashset). Map implementation classes include Hashmap,hashtable and TreeMap, first look at HashMap, combined with the following code to see:

Import java.util.*;
PublicClassmaptest{
PublicStaticvoidMainString[] (args) {
1. Create a Map collection
Map persons =NewHashMap ();The default initialization capacity for HashMap is 16, and the load factor is 0.75
2. Store key value pairs
Persons.put ("10000","JACK");
Persons.put ("10000","TOM");
Persons.put ("10001","KING");
Persons.put ("10002","PIG");
Persons.put ("10003","LINDA");
Persons.put ("10004","KIDS");
3. Determine the number of key-value pairs
The key in the map is unordered and non-repeatable, the same as HashSet
System.Out.println (Persons.size ());5
4. Determine if the collection contains such a key
System.Out.println (Persons.containskey ("10000"));True
5. Determine if the collection contains such value
System.Out.println (Persons.containsvalue ("JACK"));False
6. Get Value by key
String k="10001";
Object v=persons.Get (k);
System.Out.println (v);KING
7. Delete key value pairs via key
Persons.Remove"10002");
System.Out.println (Persons.size ());4
8. Get all the value
Collection values = Persons.values ();
Iterator It=values.iterator ();
while (It.hasnext ()) {
System.Out.println (It.next ());
}
//9. Get all keys after traversal
Set Keys=persons.keyset ();
Iterator It2=keys.iterator ();
While (It2.hasnext ()) {
Object Id=it2.next ();
Object name=persons. get (ID);
System. out.println (id+"-to" +name);
}
//10.entryset () converts a map into a set set
Set Entryset=persons.entryset ();
Iterator It3=entryset.iterator ();
While (It3.hasnext ()) {
System. out.println (It3.next ());
}
}
}

In the above code,

1. First create the Map collection persons,map persons = new HashMap (); Note here that the default initialization capacity of HashMap is 16, and the load factor is 0.75.

2.Object put (Object key,object value), adds a key-value pair to the collection, and uses the size () method to get the number of key-value pairs in the map, where the number of output key-value pairs is 5, because the 12th key repeats, So the following key-value pairs overwrite the previous key-value pairs. We can verify by System.out.println ("Jack") that the output is false, that is, the key value pair "10000", "TOM" overrides the key-value pair "10000", "Jack".

3.entrySet (); The map is converted to a set set, similar to the 9th method, but the key and the value can only be used as an equal sign, so it is generally not recommended to use the 9th method to convert the map into a set set.

Then look at Hashtable, mainly speaking about its subtype properties, the inheritance between them is as follows:

Java.lang.Object

Java.util.dictionary<k,v>

Java.util.hashtable<object,object>

Java.util.Properties

Java.util.Properties is also composed of key and value, but both key and value are string types. Combine the following code to see the main methods of properties.

Import java.util.Properties;
PublicClassmaptest02{
PublicStaticvoidMainString[] (args) {
1. Creating an Attribute Class object
Properties p=New properties ();
  //2. Save
 p.setproperty ( "Driver", "Oracle.jdbc.driver.OracleDriver");
 p.setproperty ( "username", "Scott");
       p.setproperty ( "username", "Tom");
 p.setproperty ( "password", "Tiger");
 p.setproperty ( "url", "Jdbc:oracle:thin:@192.168.1.100:1521:bjpowernode");
  //3
 string v1=p.getproperty ( "Driver");
 string v2=p.getproperty ( "username");
 string v3=p.getproperty ( "password");
 string v4=p.getproperty ( "url");
 
 system. Out.println (v1);
 system. out.println (v2);
 system. out.println (v3);
 system. out.println (v4);
 }
} /span>

After compiling the run-time output:

oracle.jdbc.driver.OracleDriver
tom
tiger
jdbc:oracle:thin:@192.168.1.100:1521:bjpowernode

In the above code, first create the Attribute class object p, and then use the SetProperty () method to store the key value pair in, the value is GetProperty ("key"); (Key is the corresponding string to be stored in). When the key is the same as in HashMap, the subsequent key-value pair overrides the previous key-value pair.

Finally, Treemap,treemap is implemented via interface SortedMap. Key features in SortedMap: unordered is not repeatable, but the elements can be automatically sorted by size, before the set of the map class can be automatically sorted, because the elements of the key part of the implementation of the comparable interface or a separate comparator is written. The code for the key part element implements the comparable interface as follows:

Importjava.util.*;
PublicClasssortedmaptest01{
PublicStaticvoidMain(string[] args) {
Map,key Storage Product,value Storage Weight
SortedMap products=NewTreeMap ();
Preparing objects
Product p1=NewProduct ("Watermelon",1.0);
Product p2=NewProduct ("Peach",4.0);
Product p3=NewProduct ("Apple",5.0);
Product p4=NewProduct ("Banana",2.0);
Add to
Products.put (P1,8.0);
Products.put (P2,3.0);
Products.put (P3,4.0);
Products.put (P4,10.0);
Traverse
Set Keys=products.keyset ();
Iterator It=keys.iterator ();
while (It.hasnext ()) {
Object K=it.next ();
Object V=products.get (k);
System.out.println (k +"--->" +v+"kg");
}
}
}
ClassProductImplementscomparable{
String name;
DoublePrice
Product (String name,DoublePrice) {
This.name=name;
This.price=price;
}
PublicStringTostring(){
Return"Product[name=" +name+", price=" +price+"]";
}
Public int&NBSP; compareTo (Object o) { &NBSP; //p1.compareto (p2);
    double price1= this.price;
    double price2= ((Product) O). Price;
  &NBSP if (price1<price2) {
      return 1;
   } else&NBSP; if (price1>price2) {
      return - 1;
   } else{
      return&NBSP; 0;
   }
 }
}

After compiling the run-time output:

Product[name=苹果,price=5.0]--->4.0kg
Product[name=桃子,price=4.0]--->3.0kg
Product[name=香蕉,price=2.0]--->10.0kg
Product[name=西瓜,price=1.0]--->8.0kg

The code for the key section element to write the comparator separately is as follows:

Importjava.util.*;
PublicClasssortedmaptest02{
PublicStaticvoidMain(string[] args) {
SortedMap products=NewTreeMap (NewProductpricecompare ());

Product p1=NewProduct ("Watermelon",2.0);
Product p2=NewProduct ("Banana",3.0);
Product p3=NewProduct ("Orange",4.0);
Product p4=NewProduct ("Pineapple",4.5);

Products.put (P1,3.2);
Products.put (P2,6.5);
Products.put (P3,5.3);
Products.put (P4,4.3);

Set Keys=products.keyset ();
Iterator It=keys.iterator ();
while (It.hasnext ()) {
Object K=it.next ();
Object V=products.get (k);
System.out.println (k +"--->" +v+"kg");
}
}
}
Classproduct{
String name;
DoublePrice
Product (String name,DoublePrice) {
This.name=name;
This.price=price;
}
PublicStringTostring(){
Return"Product[name=" +name+", price=" +price+"]";
}
}
ClassProductpricecompareImplementscomparator{
Public int Compare(Object o1,object O2) {
Double price1= ((Product) O1). Price;
Double price2= ((Product) O2). Price;
if (price1>price2) {
return 1;
}Else if (price1<price2) {
return -1;
}Else {
return 0;
}
}
}

After compiling the run-time output:

Product[name=西瓜,price=2.0]--->3.2kg
Product[name=香蕉,price=3.0]--->6.5kg
Product[name=橘子,price=4.0]--->5.3kg
Product[name=菠萝,price=4.5]--->4.3kg

Common methods for Java map classes

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.