mr.user1065741
mr.user1065741

Reputation: 692

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?

Upvotes: 11

Views: 170739

Answers (5)

Amar Prakash Pandey
Amar Prakash Pandey

Reputation: 1334

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);

Upvotes: 11

Andriya
Andriya

Reputation: 241

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.

Upvotes: 0

Illyes Istvan
Illyes Istvan

Reputation: 579

for(Room room : rooms) {
  //room contains an element of rooms
}

Upvotes: 6

Jiri Kremser
Jiri Kremser

Reputation: 12837

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);
}

Upvotes: 2

ShyJ
ShyJ

Reputation: 4650

Actually the enhanced for loop should look like this

for (final Room room : rooms) {
          // Here your room is available
}

Upvotes: 39

Related Questions