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!
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);
}
}
java-8 solution:
Stream.of(flights)
.map(f -> f.getLocations(response))
.filter(f -> f != null)
.forEach(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With