Return a list within an array list object java

Viewed 184

I'm trying to return a list of objects with specified number of seats. My ArrayList has all the objects, and I want to return all the object under a condition. It works with system output, but it doesn't return a list. I want return different object with at least seats 329.

List<Aircraft> aircraft = new ArrayList<>();

public List<Aircraft> findAircraftBySeats(int seats ) { // seats = 329

    for(int i =0; i<aircraft.size(); i++) {
        if (aircraft.get(i).getSeats() >= seats) {
             String seatss = aircraft.get(i).getModel();
             Aircraft a = new Aircraft();
             a.setModel(seatss);
             aircraft.add(a);
             System.out.println(seatss);
             return aircraft.get(a); // err The method get(int) in the type List<Aircraft> is not applicable for the arguments (Aircraft)
        }
        
    }
    return aircraft;
}

output:

Aircraft: G-AAAAwith model: 737 is a B737 with 192 seats,Statring at: MAN need aleast 4 people.

Aircraft: PH-OFDwith model: 70 is a F70 with 85 seats,Statring at: AMS need aleast 2 people.

Aircraft: PH-EZAwith model: 190 is a E190 with 50 seats,Statring at: BFS need aleast 2 people.

Aircraft: G-AAABwith model: A330 is a A330 with 329 seats,Statring at: LHR need aleast 8 people.

Aircraft: G-AAACwith model: A380 is a A380 with 489 seats,Statring at: DXB need aleast 10 people.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method get(int) in the type List<Aircraft> is not applicable for the arguments (Aircraft)

    at solution.AircraftDAO.findAircraftBySeats(AircraftDAO.java:111)
    at solution.Main.main(Main.java:28)
2 Answers

The easiest approach would probably be to stream the aircraft list and filter it:

public List<Aircraft> findAircraftBySeats(int seats) {
    return aircraft.stream()
                   .filter(a -> a.getSeats() >= seats)
                   .collect(Collectors.toList());
}

The method List.get(int a) expects an integer and in your case you're trying to access it via an object therefore an exception is thrown. To get a list of all the aircraft with a specific number of seats you have to do this:

public List<Aircraft> findAircraftBySeats(int seats ) {
    List<Aircraft> aircraftsWithLimitedSeats = new ArrayList<>();
    for (int i = 0; i < aircraft.size(); i++) {
        if (aircraft.get(i).getSeats() >= seats) {
            aircraftsWithLimitedSeats.add(aircraft.get(i));
        }
    }
    return aircraftsWithLimitedSeats;
}
Related