集册 Java实例教程 Java集合通过带有迭代器的ArrayList遍历一个集合

Java集合通过带有迭代器的ArrayList遍历一个集合

欢马劈雪     最近更新时间:2020-01-02 10:19:05

567
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
Java集合使用迭代器通过ArrayList遍历集合

import java.util.Collection;

import java.util.ArrayList;
/**
来 自 时代Java公众号 - nowjava.com
**/

import java.util.Arrays;

import java.util.Iterator;

import java.text.DateFormatSymbols;


public class OysterMonths {

    Collection<String> safeMonths;


    public Collection<String> filter(Collection<String> c) {


        Collection<String> filteredCollection = new ArrayList<String>();


        for (Iterator<String> i = c.iterator(); i.hasNext();) {
        /**
        NowJava.com - 时代Java 提供 
        **/

            String s = i.next();

            if (condition(s)) {

                filteredCollection.add(s);

            }

        }

        return filteredCollection;

    }


    public boolean condition(String s) {

        return s.contains("r");

    }


    public static void main(String[] args) {

        OysterMonths om = new OysterMonths();

        DateFormatSymbols dfs = new DateFormatSymbols();

        String[] monthArray = dfs.getMonths();

        Collection<String> months = Arrays.asList(monthArray);

        om.safeMonths = om.filter(months);

        System.out.println("The following months are safe for oysters:");

        System.out.println(om.safeMonths);

    }

}


展开阅读全文