TOD
TOD

Reputation: 91

Return count from ArrayList

I have an ArrayList that stores an inventory of cars. I want the user to input start year and end year and return a number of cars in inventory in the year range specified. I have to use a foreach loop and get all the years to display. How can I count them? Below is what I have so far

public int howManyBetweenTheseYears(int startYear, int endYear)
{
   int totalYear = 0;
   for(Lamborghini year : inventory)
   { 
      if((year.getModelYear() >= startYear)
            && (year.getModelYear() <= endYear)) {
        totalYear = year.getModelYear();
        System.out.println(totalYear);   
      }
 }    

Upvotes: 4

Views: 248

Answers (3)

romeara
romeara

Reputation: 1516

If you are able to use Java 8 constructs, another approach you could use is streams and predicates. You can get a stream view of the ArrayList, apply a predicate to it, and then get the count:

public int howManyBetweenTheseYears(int startYear, int endYear) {
    return inventory.stream()
        .filter((Lamborghini year) -> (modelYear >= startYear) && (modelYear <= endYear))
        .count();
}

What this does is get a set of Lamborghini objects from the inventory that match your condition via the filter method, and then return the count of how many items matched.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201537

You're very close. Increment totalYear and return it. Something like,

public int howManyBetweenTheseYears(int startYear, int endYear) {
    int totalYear = 0;
    for (Lamborghini year : inventory) {
        int modelYear = year.getModelYear();
        if ((modelYear >= startYear) && (modelYear <= endYear)) {
            totalYear++;
            System.out.printf("modelYear: %d, total: %d%n", modelYear, 
                    totalYear);
        }
    }
    return totalYear;
}

Upvotes: 4

gefei
gefei

Reputation: 19856

Since you want to count, you should increase totalYear by 1 for each car with a desired modelYear. I.e., change totalYear = year.getModelYear(); to

totalYear++;

BTW, if you are using Java 8, you may want to use lambdas.

Upvotes: 4

Related Questions