编程知识 cdmana.com

Four ways of traversing list in Java

 1 package com.tiandy.core.rest;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Iterator;
 5 import java.util.List;
 6 
 7 /**
 8  * List  Iterated set 
 9  * @data 2020.12.12
10  *
11  */
12 public class TestList {
13 
14     public static void main(String[] args) {
15         //  Loop traversal List Of 4 Medium method 
16         List<String> strList = new ArrayList<>();
17         strList.add("aaa");
18         strList.add("bbb");
19         strList.add("ccc");
20         //  The first one is :  Ordinary for Loop traversal mode  ( The advantage is that you can choose the subscript )
21         for (int i = 0; i < strList.size(); i++) {
22             System.out.println(strList.get(i));
23         }
24         //  The second kind :  Enhanced for loop 
25         for (String str : strList) {
26             System.out.println(str);
27         }
28         //  The third kind of :  Use Iterator iterator 
29         Iterator<String> it = strList.iterator();
30         while (it.hasNext()) {
31             String str = (String) it.next();
32             System.out.println(str);
33         }
34         //  A fourth : java8 Lambda The way ( Arrow function )
35         // strList.forEach(System.out::println); // It is equivalent to the following ( When there is only one line after it, it can be abbreviated )
36         strList.forEach(str -> {
37             System.out.println(str);
38         });
39 40     }
41 }

  If you want to be in the cycle of China , Use subscript , Recommend the first way ;

  If necessary, Zeng Qiang for loop , You can use objects directly , The second method is recommended ;

  If you need to delete elements during traversal, a third method is recommended Iterator;

  If it is JDK1.8 Above version , Pursue effect conciseness , You can use the fourth way to use forEach Arrow function .

Java Traverse Map Several ways to assemble :https://www.cnblogs.com/zhaosq/p/14103082.html

版权声明
本文为[zsq_ fengchen]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225124401067U.html

Scroll to Top