It looks like you are looking for a Java equivalent to Python's yield
keyword. Java does not have this functionality built-in.
When you say return
, you are telling Java to exit the function and return the current element. The rest of the loop does not run.
If you really want a generator functionality in Java, you might want to consider looking at the libraries mentioned in this answer.
For this specific use case, it should be sufficient to just maintain an Iterator
or an index into the collection and reference this object each time the function is called.
Iterator<Employee> myEmployeeIterator = null;
public String getEachEmployeeInstance() {
if (myEmployeeIterator == null)
myEmployeeIterator = employees.iterator();
if (myEmployeeIterator.hasNext()) {
Employee e = myEmployeeIterator.next();
return e.getFirstName() +"\t" + e.getLastName() +"\t"+ e.getEmployeeIDString()+"\t" + e.getPunchIn() +"\t"+ e.getPunchOut() +"\t"+ e.getDailyHours() +"\t"+ e.getWeeklyHours();
}
return null;
}
Another possibility is that the OP actually just wants the concatenated output from the loop, delimited by newlines, to display in his GUI component. This can be achieved most easily with StringBuilder
.
public String getEachEmployeeInstance() {
StringBuilder sb = new StringBuilder();
for (Employee e : employees)
{
sb.append(e.getFirstName() +"\t" + e.getLastName() +"\t"+ e.getEmployeeIDString()+"\t" + e.getPunchIn() +"\t"+ e.getPunchOut() +"\t"+ e.getDailyHours() +"\t"+ e.getWeeklyHours());
sb.append("\n");
}
return sb.toString();
}