Mannual
Mannual

Reputation: 3

How to sum list

HI I want to print sum of Model.length. Now it prints the list of lengths. I want to sum them.

private void initializeVehicles() {
    vehicles = new ArrayList<>();
    vehicles.add(new Car("BMW", "X3"));
    vehicles.add(new Car("Audi", "A6" ));
    vehicles.add(new Car("Mercedes", "S 63 AMG"));
    vehicles.add(new Car("Fiat", "Panda"));
}

public void modelLetterCounter(){
int sum = 0;
    for (Vehicle vehicle : vehicles) {
        if (vehicle instanceof Car) {
            int p = vehicle.getModel().length();
            sum = +p;
        }
    } System.out.println("Suma znakow to: " + sum);
  }

The consol prints:

2
2
8
5

I want to sum it and get 17.

Upvotes: 0

Views: 90

Answers (3)

Melron
Melron

Reputation: 579

Try this one

vehicles.stream().mapToInt(car -> car.getModel().length()).sum()

Upvotes: 0

Luisa Sanchez
Luisa Sanchez

Reputation: 133

Presuming the data I'm missing from your example, I guess you're looking something like this:

public void modelLetterCounter(){
  int sum = 0;
  for(Vehicle vehicle: vehicles){
      if(vehicle instanceof Car)
          sum += vehicle.getModel().length();

  }
  System.out.println(sum);
 
}

but your method seems odd to me. I don't know where vehicles list comes from in your function and second, you can actually make your method returns an int instead of printing it, and then decide what you want to do with it.

public int modelLetterCounter(List<Vehicles> vehicles){
  int sum = 0;
  for(Vehicle vehicle: vehicles){
      if(vehicle instanceof Car)
          sum += vehicle.getModel().length();

  }
  return sum;
 
}

An now call the function:

int res = modelLetterCounter(myListOfVehicles);
System.out.println(res);

Upvotes: 0

azro
azro

Reputation: 54148

You need a variable sum then add each p to it

public void modelLetterCounter() {
    int sum = 0;
    for (Vehicle vehicle : vehicles) {
        if (vehicle instanceof Car) {
            int p = vehicle.getModel().length();
            sum += p;
        }
    }
    System.out.println(sum);
}

Upvotes: 1

Related Questions