4种方式获取List中指定元素

package com.web;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Test4 {
          
   
    public static void main(String[] args) {
          
   
        // List<String> resultList = new LinkedList<>();结果也一样
        List<String> resultList = new ArrayList<>();
        resultList.add("success");
        resultList.add("error");
        resultList.add("success");
        resultList.add("warn");
        resultList.add("error");

        //1.利用equals,通过循环对比来找出你要的元素如下图所示
        int index = resultList.indexOf("warn");
        System.out.println("index = " + index);
        // index = 3
        System.out.println(resultList.get(index));

        //2.直接get,根据add进去的顺序找出你需要的元素
        for (String s :
                resultList) {
          
   
            if (("error").equals(s)) {
          
   
                System.out.println(s);
            }
        }

        //3.你也可以通过indexOf(赛选条件)找到元素的下表,然后get出来
       // -1 if this list does not contain the element.
        if (resultList.indexOf("warn") != -1) {
          
   
            System.out.println(resultList.get(resultList.indexOf("warn")));
        }

       //使用Iterator迭代器获取
        Iterator it = resultList.iterator();
        while (it.hasNext()){
          
   
            String str = (String) it.next();
            if ("success".equals(str)){
          
   
                System.out.println("str = " + str);
            }
        }

    }
}
经验分享 程序员 微信小程序 职场和发展