Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access method GetEmployeeDetails() using iterator object

Tags:

java

How can I call getEmployeeDetails() method using Iterator Object?

Java:

import java.util. * ;

class Employee {
    String empName;
    int empId;
    String email;
    String gender;
    float salary;
    public void GetEmployeeDetails() {
        System.out.println(empName + " " + empId + "   " + email + "    " + gender + "    " + salary);
    }
    Employee(String empName, int empId, String email, String gender, float salary) {
        this.empName = empName;
        this.empId = empId;
        this.email = email;
        this.gender = gender;
        this.salary = salary;
    }
}

public class EmployeeDB {
    public static void main(String[] args) {
        ArrayList<Employee> list=new ArrayList<Employee>();
        Scanner sc = new Scanner(System. in );
        System.out.println("Please Enter Number of Employee : ");
        int empcount = sc.nextInt();
        for (int i = 0; i < empcount; i++) {
            System.out.println("Please enter the Employee name :");
            String empName = sc.next();
            int empId = sc.nextInt();
            String email = sc.next();
            String gender = sc.next();
            float salary = sc.nextFloat();

            Employee emp = new Employee(empName, empId, email, gender, salary);
            list.add(emp);
            //list.add(emp);
        }
        Iterator itr = list.iterator();
        while (itr.hasNext()) {
            Employee i = (Employee) itr.next();
            System.out.println(i.empName);
        }
        Employee e = list.get(0);
        System.out.println(e);
    }
}
like image 679
Somesh Gangwar Avatar asked Feb 25 '26 15:02

Somesh Gangwar


1 Answers

Your code will like bellow using Iterator

for (Iterator<Employee> it = list.iterator(); it.hasNext(); ) {
                it.next().GetEmployeeDetails();
            }

Here it.next() will return the employee object. Once you get the Employee object then you can call GetEmployeeDetails() method

You can use for each loop using bellow way:

for (Employee employee:list) {
            employee.GetEmployeeDetails();
        }

Using lambda expression, you can use bellow code:

list.forEach(employee -> employee.GetEmployeeDetails());
like image 62
Md. Sajedul Karim Avatar answered Feb 28 '26 05:02

Md. Sajedul Karim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!