'Foreach loop in java for a custom object list
I have an ArrayList for type Room (my custom object) Defined as below
ArrayList<Room> rooms = new ArrayList<Room>();
After then adding a series of objects to the ArrayList I want to go through them all and check various things. I am not a keen user of java but I know in many other programming languages a foreach loop would be the most simple way of doing this.
After a bit of research I found the following link which suggests the code below. How does the Java 'for each' loop work?
for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
But as far as I can tell this cant be used for an Arraylist of a custom object.
Can, and if so how can I implement a foreach loop for an ArrayList of a custom object? Or how could I otherwise process each item?
Solution 1:[1]
Actually the enhanced for loop should look like this
for (final Room room : rooms) {
// Here your room is available
}
Solution 2:[2]
You can also use Java 8 stream API and do the same thing in one line.
If you want to print any specific property then use this syntax:
ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> System.out.println(room.getName()));
OR
ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(room -> {
// here room is available
});
if you want to print all the properties of Java object then use this:
ArrayList<Room> rooms = new ArrayList<>();
rooms.forEach(System.out::println);
Solution 3:[3]
for(Room room : rooms) {
//room contains an element of rooms
}
Solution 4:[4]
You can fix your example with the iterator pattern by changing the parametrization of the class:
List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Iterator<Room> i = rooms.iterator(); i.hasNext(); ) {
String item = i.next();
System.out.println(item);
}
or much simpler way:
List<Room> rooms = new ArrayList<Room>();
rooms.add(room1);
rooms.add(room2);
for(Room room : rooms) {
System.out.println(room);
}
Solution 5:[5]
If this code fails to operate on every item in the list, it must be because something is throwing an exception before you have completed the list; the likeliest candidate is the method called "insertOrThrow". You could wrap that call in a try-catch structure to handle the exception for whichever items are failing without exiting the loop and the method prematurely.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ShyJ |
| Solution 2 | Skelly |
| Solution 3 | Illyes Istvan |
| Solution 4 | Jiri Kremser |
| Solution 5 | Andriya |
