Java traverses the map key, the value. Ways to get the map size

Source: Internet
Author: User

Map read key-value pairs, Java traversal map two implementation methods

The first method is to get the set set of the key based on the map's keyset () method, and then traverse the map to get the value

ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Set; Public classhashmaptest2{ Public Static voidMain (string[] args) {HashMap map=NewHashMap (); Map.put ("A", "AAAA"); Map.put ("B", "BBBB"); Map.put ("C", "CCCC"); Map.put ("D", "dddd"); Set Set=Map.keyset ();  for(Iterator iter =set.iterator (); Iter.hasnext ();) {String key=(String) iter.next (); String value=(String) map.get (key); SYSTEM.OUT.PRINTLN (Key+"===="+value); } }}

The second approach is to use Map.entry to obtain:

ImportJava.util.HashMap;ImportJava.util.Iterator;ImportJava.util.Map;ImportJava.util.Set; Public classhashmaptest4{ Public Static voidMain (string[] args) {HashMap map=NewHashMap (); Map.put ("A", "AA"); Map.put ("B", "BB"); Map.put ("C", "CC"); Map.put ("D", "DD"); Set Set=Map.entryset ();  for(Iterator iter =set.iterator (); Iter.hasnext ();) {Map.entry Entry=(Map.entry) iter.next (); String Key=(String) Entry.getkey (); String value=(String) entry.getvalue (); SYSTEM.OUT.PRINTLN (Key+" :" +value); } }}

To get the map size method:

 Public Static void Main (string[] args) {    new  HashMap ();    Map.put ("Apple", "fresh Apple");     // add data to the list     map.put ("Computer", "well-equipped computer");   // add data to the list     map.put ("book", "books piled up into a mountain");     // add data to the list     System.out.println ("Map collection size is:" +map.size ());}

Java traverses the map key, the value. Ways to get the map size

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.