search
HomeJavajavaTutorialJava Example - Collection Traversal

The following example demonstrates how to traverse a collection of List, Set and Map types that are stored in the form of key-value pairs extended from the Collection interface. Below we use ordinary for, enhanced for, iterator and other methods to traverse. Collections:

Traversal of List and Set type collections

/*
 author by w3cschool.cc
 Main.java
 */import java.util.ArrayList;import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;import java.util.Set;
 public class Main {

   public static void main(String[] args) {
      // List集合的遍历
      listTest();
      // Set集合的遍历
      setTest();
   }

   private static void setTest() {
      Set<String> set = new HashSet<String>();
      set.add("JAVA");
      set.add("C");
      set.add("C++");
      // 重复数据添加失败
      set.add("JAVA");
      set.add("JAVASCRIPT");

      // 使用iterator遍历set集合
      Iterator<String> it = set.iterator();
      while (it.hasNext()) {
         String value = it.next();
         System.out.println(value);
      }
      
      // 使用增强for循环遍历set集合
      for(String s: set){
         System.out.println(s);
      }
   }

   // 遍历list集合
   private static void listTest() {
      List<String> list = new ArrayList<String>();
      list.add("菜");
      list.add("鸟");
      list.add("教");
      list.add("程");
      list.add("www.w3cschool.cc");

      // 使用iterator遍历
      Iterator<String> it = list.iterator();
      while (it.hasNext()) {
         String value = it.next();
         System.out.println(value);
      }

      // 使用传统for循环进行遍历
      for (int i = 0, size = list.size(); i < size; i++) {
         String value = list.get(i);
         System.out.println(value);
      }

      // 使用增强for循环进行遍历
      for (String value : list) {
         System.out.println(value);
      }
   }}

The output result of running the above code is:

菜鸟教程www.w3cschool.cc菜鸟教程www.w3cschool.cc菜鸟教程www.w3cschool.cc
JAVA
JAVASCRIPT
C++C
JAVA
JAVASCRIPT
C++C

About traversal of Map type collections

The following examples We used the keySet() and entrySet() methods of HashMap to traverse the collection:

/*
 author by w3cschool.cc
 Main.java
 */import java.util.Map;import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;import java.util.List;import java.util.Set;
 import java.util.Map.Entry;//增强For循环public class Main {

   public static void main(String[] args) {
      // 创建一个HashMap对象,并加入了一些键值对。
      Map<String, String> maps = new HashMap<String, String>();
      maps.put("1", "PHP");
      maps.put("2", "Java");
      maps.put("3", "C");
      maps.put("4", "C++");
      maps.put("5", "HTML");
      
      // 传统的遍历map集合的方法1; keySet()
      //traditionalMethod1(maps);
      // 传统的遍历map集合的方法2; entrySet()
      //traditionalMethod2(maps);
      // 使用增强For循环来遍历map集合方法1; keySet()
      //strongForMethod1(maps);
      // 使用增强For循环来遍历map集合方法2; entrySet()
      strongForMethod2(maps);
   }

   private static void strongForMethod2(Map<String, String> maps) {
      Set<Entry<String, String>> set = maps.entrySet();
      for (Entry<String, String> entry : set) {
         String key = entry.getKey();
         String value = entry.getValue();
         System.out.println(key + " : " + value);
      }
   }

   private static void strongForMethod1(Map<String, String> maps) {
      Set<String> set = maps.keySet();
      for (String s : set) {
         String key = s;
         String value = maps.get(s);
         System.out.println(key + " : " + value);
      }
   }

   // 使用entrySet()方法,获取maps集合中的每一个键值对,
   private static void traditionalMethod2(Map<String, String> maps) {
      Set<Map.Entry<String, String>> sets = maps.entrySet();
      // 取得迭代器遍历出对应的值。
      Iterator<Entry<String, String>> it = sets.iterator();
      while (it.hasNext()) {
         Map.Entry<String, String> entry = (Entry<String, String>) it.next();
         String key = entry.getKey();
         String value = entry.getValue();
         System.out.println(key + " : " + value);
      }
   }

   // 使用keySet()方法,获取maps集合中的所有键,遍历键取得所对应的值。
   private static void traditionalMethod1(Map<String, String> maps) {
      Set<String> sets = maps.keySet();
      // 取得迭代器遍历出对应的值
      Iterator<String> it = sets.iterator();
      while (it.hasNext()) {
         String key = it.next();
         String value = maps.get(key);
         System.out.println(key + " : " + value);
      }
   }}


The output result of running the above code is:

1 : PHP
2 : Java
3 : C
4 : C++
5 : HTML

The above is Java Example - Collection traversal content, please pay attention to the PHP Chinese website (www.php.cn) for more related content!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),