Skip to content

Display ArrayList data using Foreach in Java

This post explains a simple ArrayList program to add employee details and to display ArrayList data using foreach loop in Java. If you would like to display the arrayList data on a JSP page, go through the following link.

DisplayArrayList.java

package com.arraylist;

import java.util.*;

class Employee{
	public int id;
	public String name;
	public String city;
	public static int count = 0;

	//zero argument constructor. Gets called by default when an object is created for the Employee class
	public Employee(){}

	//Parameterized Constructor
	public Employee(int id, String name,String city)
	{
		super();
		this.id = id;
		this.name = name;
		this.city=city;
		count++;
	}

	public int getId() {
	return id;
	}

	public String getName() {
	return name;
	}

	public String getAddress() {
	return city;
	}
}

public class DisplayArrayList {
public static void main(String[] args) throws Exception 
	{
	 List<Employee> list = new ArrayList<Employee>();

	 list.add(new Employee(1, "Ravi","Delhi"));
	 list.add(new Employee(2, "Raj","Mumbai"));
	 list.add(new Employee(3, "Rekha","Chennai"));
	 list.add(new Employee(4, "Ram","Siliguri"));

		for (Employee s : list) //Iterates as long as there are elements in the list. An object s is created of type Employee class.
		{
			System.out.print("ID, Name and City of the employee are : ");
			System.out.println(s.getId()+" "+s.getName()+" " +s.getAddress());
		}
	}//End of main() method
}//end of DisplayArrayList class

The output of the program is shown in the following picture.

5 thoughts on “Display ArrayList data using Foreach in Java”

  1. blank

    hi, if i have a list of 50 items or employee, and need to display only 10 items in page, and if user want see another 10 items, need to click button to see next 10 items. how i can do that?

  2. blank

    hey if we create a display() method in employee class. how can we call that method in foreach loop
    in your java code

    1. blank

      Please try the below method.
      You can call this function in the Employee class.

      void display(List employees)
      {
      for (Employee s : employees) //Iterates as long as there are elements in the list. An object s is created of type Employee class.
      {
      System.out.print("ID, Name and City of the employee are : ");
      System.out.println(s.getId()+" "+s.getName()+" " +s.getAddress());
      }
      }

      In Main class,
      Employee emp = new Employee();
      emp.display(list)

Did it help? Would you like to express?