Summary of four methods of Java map traversal _java

Source: Internet
Author: User

Sorted out four ways to traverse a map in Java:

Import Java.util.hashmap;import java.util.iterator;import Java.util.map;import Java.util.map.entry;import Java.util.set;publicclassmaptest{privatemap<string,string> Map;publicmaptest () {
Map =newhashmap<string,string> ();
Map.put ("1", "first number");
Map.put ("2", "second number");
  map.put ("3", "third Number");} The first method (traditional method) Publicvoid Mapone () {set<string> Set = Map.keyset ();iterator<string> it = Set.iterator (); while (It.hasnext ()) {string key = (String) it.next (); String value = (string) map.get (key); SYSTEM.OUT.PRINTLN (key + "=" + value);} The second method (traditional method) Publicvoid Maptwo () {Set set = Map.entryset (); Iterator it = Set.iterator (); while (It.hasnext ()) {Entry Entry = (Entry) it.next (); String key = (string) entry.getkey (); String value = (string) entry.getvalue (); SYSTEM.OUT.PRINTLN (key + "=" + value);} The third method (enhanced for-loop method) Publicvoid Mapthree () {for (Object Obj:map.keySet ()) {String key = (string) obj; String value = (string) map.get (key); SYSTEM.OUT.PRINTLN (key + "=" + value);} The fourth method (enhanced for-loop method) Publicvoid Mapfour () {for (Object Obj:map.entrySet ()) {Entry Entry = (Entry) obj; String key = (string) entry.getkey (); String value = (string) entry.getvalue (); SYSTEM.OUT.PRINTLN (key + "=" + value);} Publicstaticvoid Main (string[] args) {maptest maptest =newmaptest (); System.out.println ("=====first===== ");
Maptest.mapone (); System.out.println ("=====second=====");
Maptest.maptwo (); System.out.println ("=====three=====");
Maptest.mapthree (); System.out.println ("=====four=====");
Maptest.mapfour ();} Output results:

=====first=====3= Third Number 2 = second Number 1 = first number =====second=====3= Third number 2 = second Number 1 = first number =====three=====3= Third number 2 = second Number 1 = first number =====four= ====3= Third Number 2 = second Number 1 = first number

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.