Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 712
NatalieHants Avatar asked Nov 17 '25 12:11

NatalieHants


2 Answers

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);
    }
}
like image 131
Rick Avatar answered Nov 19 '25 01:11

Rick


java-8 solution:

Stream.of(flights)
        .map(f -> f.getLocations(response))
        .filter(f -> f != null)
        .forEach(System.out::println);
like image 37
Bilesh Ganguly Avatar answered Nov 19 '25 02:11

Bilesh Ganguly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!