Simpler way to do it...
ArrayList<MyObject> list = ...
for( MyObject obj : list)
obj.count()
Answer from raffian on Stack OverflowSimpler way to do it...
ArrayList<MyObject> list = ...
for( MyObject obj : list)
obj.count()
You have several ways to do so:
Basic1:
n = 0;
while (n < arrayList.size()) {
(arrayList.get(n)).count();
n++;
}
Basic2:
for (int i = 0; i < arrayList.size(); i++) {
(arrayList.get(i)).count();
}
Better1:
for(ClassTypeOfArrayList item: arrayList) {
item.count();
}
Better2:
Iterator iterator = arrayList.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
Iterating through an arrayList of objects
For-each loop ArrayList
How do you efficiently loop through a linkedlist?
Why does the List interface have forEach, but not map?
Videos
Hello! I am trying to iterate through an ArrayList and having trouble with getting my loop right. I am trying to use an advanced for loop (the method I figured would be easier for me to understand) to iterate through an arrayList of objects that is some 60,000 records in a database. Basically I need to ask the user for an employee ID and the program is supposed to search the database for it and if it exist then it prints out the info associated to the ID (last name, first name, birthdate). I have all the code right for the database part but I am stuck on getting the program to print the info. I know I need to create the scanner object, the loop, and then somehow use get methods right? Any help would be appreciated!
Here is some of the code I have if it helps:
public static void main(String\[\] args) {
ArrayList<Employee> emp = getDBData();
searchEmployee(emp);
}
//Search Employee method...
private static void searchEmployee(ArrayList<Employee> emp) {
}
//My arrayList
ArrayList<Employee> set = new ArrayList<Employee>();
//The loop
Scanner scanner = new Scanner(System. in);
System.out.println("Enter the Employee ID to search: ");
String empID = scanner.nextLine();
for(Employee emp: set){
System.out.println(empID);
}I am in the third part of a MOOC course on Java. And I'm a little confused about the ambiguity of using the For-each loop to enumerate a list.
Consider the following list as an example
ArrayList<Integer> list = new ArrayList<>();
The examples and answers present two implementations:
for (Integer val: list) {
//do something
}
for (int val: list) {
//do something
}
But it is not explained how one differs from the other and when one or the other variant should be used. Please tell me the difference between the two.