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);
}
}
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With