[Java] 5 ways to traverse the list collection

Ordinary is just two words: laziness and laziness;
success is just two words: hardship and diligence;
excellence is just two words: you and me.
Follow me to learn JAVA, spring family bucket and linux operation and maintenance knowledge from 0, and take you from an ignorant teenager to the peak of life, and marry Bai Fumei!
Follow the WeChat public account [ IT is very reliable  ], and share technical experience every day~ 

 

[Java] 5 ways to traverse the list collection

 

      List collections are very common in daily Java development. Quickly selecting the appropriate traversal method can greatly improve our development efficiency. Below I summarize the five ways to traverse the List collection:

      1) Ordinary traversal: for(int i=0; i< arrays.size(); i++)

      2) Enhanced for traversal: for(String str: arrays)

      3)list.forEach((str) -> xxxxx)

      4) Use Iterator to traverse

      5) java8 stream traversal

      Note: for (int i=0; i< arrays.size(); i++) ordinary traversal can manipulate an object by index, but the other 4 traversal methods cannot.

 

Test code:

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Main {

  public static void main(String[] args) {

    //要遍历的list集合
    List<String> arrays = Arrays.asList("张三", "李四", "王五", "小六", "老七");

    //1. for(int i=0; i< arrays.size(); i++)
    log.info("=================for(int i=0; i< arrays.size(); i++)普通遍历==========");
    for (int i = 0; i < arrays.size(); i++) {
      log.info(arrays.get(i));
    }

    //2. 增强for(String str : arrays)
    log.info("=================增强for(String str : arrays)遍历=====================");
    for (String str : arrays) {
      log.info(str);
    }

    //3. list.forEach((str) -> xxxxx)
    log.info("=================arrays.forEach((str) -> xxxxx)遍历===================");
    arrays.forEach(str -> log.info(str));

    //4. 使用Iterator迭代器遍历
    log.info("=================使用Iterator迭代器遍历================================");
    Iterator<String> it = arrays.iterator();
    while (it.hasNext()) {
      String str = (String) it.next();
      log.info(str);
    }

    //5. java8 stream流遍历
    log.info("=================java8 stream遍历=====================================");
    arrays.stream()
        //过滤掉“王五”
        .filter(str -> !Objects.equals("王五", str))
        .forEach(str -> log.info(str));
  }
}

 

Test Results:

      Follow the WeChat public account, reply " I want java video tutorial " to get java video tutorial for free~

 

Guess you like

Origin blog.csdn.net/IT_Most/article/details/109158487