Return count from ArrayList

I have ArrayList, in which the inventory of cars is stored. I want the user to enter the start year and end of the year and return the number of cars in the inventory in the specified range of the year. I have to use the foreach loop and get all the years to display. How can I count them? The following is what I still have

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);   
      }
 }    
+4
source share
3 answers

You are very close. Increment totalYearand returnit. Sort of,

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;
}
+4
source

Since you want to calculate, you must increase totalYearby 1 for each car with the desired modelYear. Ie change totalYear = year.getModelYear();to

totalYear++;

, Java 8, lambdas.

+4

If you can use the Java 8 constructors, another approach you can use is threads and predicates. You can get a representation of the ArrayList stream, apply a predicate to it, and then get a counter:

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

What this means is to get a set of Lamborghini objects from the inventory that matches your condition using the method filter, and then return the number of matching items.

0
source

Source: https://habr.com/ru/post/1618229/


All Articles