Search code examples
javaandroidforeachhashmaplinkedhashmap

Incrementing counter in LinkedHashMap using foreach-loop


I am looping through a LinkedHashMap and incrementing i counter and below is how I used to do it using a for-loop.

int i = 0;

for (Map.Entry<String, String> entry : linkedHashMap.entrySet()) {
      Car car = new Car();

      car.setCarId(String.valueOf(i++));
      car.setCarName(entry.getKey());
      car.setOdometerReading(entry.getValue());

      appRoomRepository.insertCarDetails(car);
}

Below is how I want to use a foreach-loop

int i = 0;

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
     linkedHashMap.forEach((key, value) -> {
           Car car = new Car();

           car.setCarId(String.valueOf(i++));
           car.setCarName(key);
           car.setOdometerReading(value);

           appRoomRepository.insertCarDetails(car);
        });
}

I am stuck in this line car.setCarId(String.valueOf(i++));

I keep getting this error "Variable used in lambda expression should be final or effectively final". How can I increment counter i?


Solution

  • Lambda expressions can use variables defined in an outer scope They can capture static variables, instance variables, and local variables, but only local variables must be final or effectively final

    Use AtomicInteger:

    AtomicInteger i = new AtomicInteger(0);
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    
         linkedHashMap.forEach((key, value) -> {
    
               Car car = new Car();
    
               car.setCarId(String.valueOf(i.getAndIncrement()));
               car.setCarName(entry.getKey());
               car.setOdometerReading(entry.getValue());
    
               appRoomRepository.insertCarDetails(car);
    
            });
    }
    
    ```