如何在Java中迭代列表

时间:2020-02-23 14:34:21  来源:igfitidea点击:

在本教程中,我们将看到如何在Java中迭代列表。
有四种方法可以通过列表迭代。

  • 对于循环
  • 对于每个循环(Java 5)
  • 循环时
  • 迭代器

下面的示例将帮助您理解如何在java中迭代列表
。我采取自定义对象列表,以更好地了解

1.Country.java.

package org.igi.theitroad;
public class Country {
 
	String name;
	long population;
 
	public Country(String name, long population) {
		super();
		this.name = name;
		this.population = population;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getPopulation() {
		return population;
	}
	public void setPopulation(long population) {
		this.population = population;
	} 
 
}
  1. iteratelistmain.java.
package org.igi.theitroad;
 
import java.util.ArrayList;
import java.util.Iterator;
 
public class IterateListMain {
	/**
	 * @author igi Mandliya
	 */
	public static void main(String[] args) {
 
		Country Netherlands=new Country("Netherlands",1000);
		Country japan=new Country("Japan",10000);
 
		Country france=new Country("France",2000);
		Country russia=new Country("Russia",20000);
 
		//We are going to iterate on this list and will print 
		//name of the country 
		ArrayList countryLists=new ArrayList();
		countryLists.add(Netherlands);
		countryLists.add(japan);
		countryLists.add(france);
		countryLists.add(russia);
 
		//For loop
		System.out.println("Iterating using for loop : ");
		for (int i = 0; i < countryLists.size(); i++) {
			Country countryObj=countryLists.get(i);
			System.out.println(countryObj.getName());
		}
		System.out.println("-----------------------------");
 
		//For each loop
		System.out.println("Iterating using for each loop : ");
		for (Country countryObj:countryLists) {
			System.out.println(countryObj.getName());
		}
		System.out.println("-----------------------------");
 
		//While loop
		System.out.println("Iterating using while loop : ");
		int i=0;
		while(i<countryLists.size())
		{
			Country countryObj=countryLists.get(i);
			System.out.println(countryObj.getName());
			i++;
		}
 
		System.out.println("-----------------------------");
 
		//Iterator
		System.out.println("Iterating using iterator : ");
		Iterator iteratorCountryLists= countryLists.iterator();
		while(iteratorCountryLists.hasNext())
		{
			System.out.println(iteratorCountryLists.next().getName());
		}
 
	}
}

运行它,我们将获取以下输出:

Iterating using for loop : 
Netherlands
Japan
France
Russia
----------------------------
Iterating using for each loop : 
Netherlands
Japan
France
Russia
----------------------------
Iterating using while loop : 
Netherlands
Japan
France
Russia
----------------------------
Iterating using iterator : 
Netherlands
Japan
France
Russia