NatalieHants
NatalieHants

Reputation: 57

Java - Loop through instances of a class rather than calling a method for each separate instance

I am starting to learn Java and would like to know how to loop through instances of a class when calling a method, instead of separately calling the method for each instance, like below:

String potentialFlight = (Flight1.getLocations(response));
if (potentialFlight != null) {
    System.out.println(potentialFlight);
}

potentialFlight = (Flight2.getLocations(response));
if (potentialFlight != null) {
    System.out.println(potentialFlight);
}

For clarity, Flight1 and Flight2 are instances of a class Flight. Response is the user input parsed into the method and will be a location, which I will use the getLocations method to return any potential flights departing from that location.

If you need more of my code, please comment below.

Thanks for you help!

Upvotes: 3

Views: 9683

Answers (3)

Bilesh Ganguly
Bilesh Ganguly

Reputation: 4131

solution:

Stream.of(flights)
        .map(f -> f.getLocations(response))
        .filter(f -> f != null)
        .forEach(System.out::println);

Upvotes: 2

Mad Matts
Mad Matts

Reputation: 1116

You should probably use interfaces for flexible handling e.g.:

public interface IFlyingObject {

    Object getLocations(Object o);

}

public class Plane implements IFlyingObject{
    @Override
    public Object getLocations(Object o) {
        return null;
    }
}
public class Helicopter implements IFlyingObject{
    @Override
    public Object getLocations(Object o) {
        return null;
    }
}
public static void main(String[] args) {
    List<IFlyingObject> flightObjects = new ArrayList<IFlyingObject>();
    flightObjects.add(new Plane());
    flightObjects.add(new Helicopter());
    Object response = new Object();
    for (IFlyingObject f : flightObjects) {
        Object result = f.getLocations(response);
    }
}

Upvotes: 0

Rick
Rick

Reputation: 443

You could put all your instances into an Array(List), and use a foreach construction to iterate over all instances.

For example:

Flight[] flights = { Flight1, Flight2 };
for (Flight f : flights) {
    String potentialFlight = (f.getLocations(response));
    if (potentialFlight != null) {
        System.out.println(potentialFlight);
    }
}

Upvotes: 6

Related Questions