Home » Uncategorized » ForEach von Java 8 Collections mit Lambda: Limitierung bei int Laufvariable/Counter

ForEach von Java 8 Collections mit Lambda: Limitierung bei int Laufvariable/Counter

public class LambdaForEach
{
    public static void main( String[] args )
    {
        List<String> myList = Arrays.asList("A", "B");

        // NOT possible:
        //Error: Variable used in lambda expression should be final or effectively final
        // int i = 1;
        // myList.forEach(item -> System.out.println("Item number " + i++ + "is " + item )); 
        
        //Stattdessen soll man das so machen:
        final AtomicInteger atomicInteger = new AtomicInteger(0);
        myList.forEach(item -> System.out.println("Item number " + atomicInteger.incrementAndGet() + " is " + item )); //Error: Variable used in lambda expression should be final or effectively final

        //Warum denn nicht so?
        int i = 0;
        for(String item : myList){
            System.out.println("Item number " + ++i + " is " + item );
        }
    }
}
// Output:
//    Item number 1 is A
//    Item number 2 is B
//    Item number 1 is A
//    Item number 2 is B

Diskussion auf:
https://stackoverflow.com/questions/28790784/java-8-preferred-way-to-count-iterations-of-a-lambda


Hinterlasse einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert