You have forgotten the generics on your BiFunction:

public static void main(final String[] args) throws Exception {
    final Map<String, Integer> map = new HashMap<>();
    map.put("A", 1);
    map.put("B", 2);
    map.put("C", 3);
    final BiFunction<String, Integer, Integer> remapper = (k, v) -> v == null ? 42 : v + 41;
    map.compute("A", remapper);
}

Running:

PS C:\Users\Boris> java -version
java version "1.8.0-ea"
Java(TM) SE Runtime Environment (build 1.8.0-ea-b120)
Java HotSpot(TM) 64-Bit Server VM (build 25.0-b62, mixed mode)
Answer from Boris the Spider on Stack Overflow
🌐
W3Schools
w3schools.com › java › java_lambda.asp
Java Lambda Expressions
Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting ... How Tos Add Two Numbers Swap Two Variables Even or Odd Number Reverse a Number Positive or Negative Square Root Area of Rectangle Celsius to Fahrenheit Sum of Digits Check Armstrong Num Random Number Count Words Count Vowels in a String Remove Vowels Count Digits in a String Reverse a String Palindrome Check Check Anagram Convert String to Array Remove Whitespace Count Character Frequency Sum of Array Elements Find Array Average Sort an Array Find Smallest Element Find Largest Element Second Largest Array Min and Max Array Merge Two Arrays Remove Duplicates Find Duplicates Shuffle an Array Factorial of a Number Fibonacci Sequence Find GCD Check Prime Number ArrayList Loop HashMap Loop Loop Through an Enum
🌐
Jenkov
jenkov.com › tutorials › java › lambda-expressions.html
Java Lambda Expressions
The var keyword was introduced in Java 10 as local variable type inference. From Java 11 var can also be used for lambda parameter types. Here is an example of using the Java var keyword as parameter types in a lambda expression: Function<String, ...
🌐
Medium
codesnoob.medium.com › java-8-local-variables-and-lambda-function-4ce96f80c97a
Java 8 — Local Variables and Lambda Function - Sreenidhi KV
June 10, 2022 - How to manipulate the local variables of a method, that get’s consumed by Lambda function? Can use Atomic References eg, AtomicIntegers which ensures concurrency. Although we shouldn’t be manipulating local variables inside lambdas. ... Don’t get confused! Final ensures that the reference never changes, the value can change! As shown below. import java.util.ArrayList; import java.util.Arrays; import java.util.List; @FunctionalInterface interface PrintCoin{ void print(); } class Doge{ public void getDoge(){ int coin = 100; List<Integer> coinsBought = new ArrayList(); PrintCoin printCoin =
Top answer
1 of 10
325

Use a wrapper

Any kind of wrapper is good.

With Java 10+, use this construct as it's very easy to setup:

var wrapper = new Object(){ int ordinal = 0; };
list.forEach(s -> {
  s.setOrdinal(wrapper.ordinal++);
});

With Java 8+, use either an AtomicInteger:

AtomicInteger ordinal = new AtomicInteger(0);
list.forEach(s -> {
  s.setOrdinal(ordinal.getAndIncrement());
});

... or an array:

int[] ordinal = { 0 };
list.forEach(s -> {
  s.setOrdinal(ordinal[0]++);
});

Note: be very careful if you use a parallel stream. You might not end up with the expected result. Other solutions like Stuart's might be more adapted for those cases.

For types other than int

Of course, this is still valid for types other than int.

For instance, with Java 10+:

var wrapper = new Object(){ String value = ""; };
list.forEach(s->{
  wrapper.value += "blah";
});

Or if you're stuck with Java 8 or 9, use the same kind of construct as we did above, but with an AtomicReference...

AtomicReference<String> value = new AtomicReference<>("");
list.forEach(s -> {
  value.set(value.get() + s);
});

... or an array:

String[] value = { "" };
list.forEach(s-> {
  value[0] += s;
});
2 of 10
26

This is fairly close to an XY problem. That is, the question being asked is essentially how to mutate a captured local variable from a lambda. But the actual task at hand is how to number the elements of a list.

In my experience, upward of 80% of the time there is a question of how to mutate a captured local from within a lambda, there's a better way to proceed. Usually this involves reduction, but in this case the technique of running a stream over the list indexes applies well:

IntStream.range(0, list.size())
         .forEach(i -> list.get(i).setOrdinal(i));
🌐
TutorialsPoint
tutorialspoint.com › how-to-declare-a-variable-within-lambda-expression-in-java
How to declare a variable within lambda expression in Java?
import java.util.*; public class LambdaTest { public static void main(String args[]) { final String[] country = {null}; List cities = new ArrayList(); cities.add("Hyderabad"); cities.add("Ireland"); cities.add("Texas"); cities.add("Cape Town"); cities.forEach(item -> { // lambda expression if(item.equals("Ireland")) country[0] = "UK"; // variable array }); System.out.println(country[0]); } } UK ·
🌐
Baeldung
baeldung.com › home › java › java local variable syntax for lambda parameters
Java Local Variable Syntax for Lambda Parameters | Baeldung
January 8, 2024 - The local variable syntax for lambda parameters is the only language feature introduced in Java 11. In this tutorial, we’ll explore and use this new feature. One of the key features introduced in Java 10 was local variable type inference. It allowed the use of var as the type of the local variable instead of the actual type. The compiler inferred the type based on the value assigned to the variable.
🌐
Oracle
docs.oracle.com › javase › tutorial › java › javaOO › lambdaexpressions.html
Lambda Expressions (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
To determine the type of a lambda expression, the Java compiler uses the target type of the context or situation in which the lambda expression was found. It follows that you can only use lambda expressions in situations in which the Java compiler can determine a target type: Variable declarations · Assignments ·
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-lambda-expression-variable-capturing-with-examples
Lambda Expression Variable Capturing with Examples - GeeksforGeeks
October 25, 2025 - Lambda expression can outlive their defining method. To ensure consistency, they can capture only local variables that are final or effectively final, guaranteeing predictable, unchanging values. ... import java.util.*; public class GFG{ public static void main(String[] args){ List<Runnable> tasks = new ArrayList<>(); for (int i = 0; i < 3; i++){ // Effectively final variable int temp = i; tasks.add( () -> System.out.println("Value: " + temp)); } tasks.forEach(Runnable::run); } }
🌐
Rice
clear.rice.edu › comp310 › JavaResources › lambdas.html
Lambda Functions
Lambda functions in Java assume that there is a "functional" interface defined somewhere. A "functional interface" is simply an interface that defines a single method. This associated interface is related to the lambda function only in that it is the "target" type to which the lambda is being assigned, either by variable assignment or by passing the lambda as an input parameter or output parameter of a method which is typed to that interface.
🌐
InformIT
informit.com › articles › article.aspx
3.7 Lambda Expressions and Variable Scope | Java Interfaces and Lambda Expressions | InformIT
A new variable arg is created in each iteration and assigned the next value from the args array. In contrast, the scope of the variable i in the preceding example was the entire loop. As a consequence of the “effectively final” rule, a lambda expression cannot mutate any captured variables.
🌐
TutorialsPoint
tutorialspoint.com › what-are-the-rules-for-a-local-variable-in-lambda-expression-in-java
What are the rules for a local variable in lambda expression in Java?
July 11, 2020 - A lambda expression can't define ... scope of a lambda expression. Inside lambda expression, we can't assign any value to some local variable declared outside the lambda expression....
🌐
Baeldung
baeldung.com › home › java › lambda expressions and functional interfaces: tips and best practices
Lambda Expressions and Functional Interfaces: Tips and Best Practices | Baeldung
December 16, 2023 - In this situation, it is very useful to use another Java 8 feature, method references. ... This is not always shorter, but it makes the code more readable. Accessing a non-final variable inside lambda expressions will cause a compile-time error, but that doesn’t mean that we should mark every target variable as final. According to the “effectively final” concept, a compiler treats every variable as final as long as it is assigned ...
🌐
Stack Abuse
stackabuse.com › lambda-expressions-in-java
Lambda Expressions in Java
May 8, 2019 - If the lambda and the interface match, the lambda function can be assigned to a variable of that interface's type.
🌐
Medium
medium.com › @lavishj77 › java-lambda-expressions-4ea3b8245196
Java Lambda Expressions. One of the big new feature added in… | by Lavish Jain | Medium
January 21, 2022 - It let you to create these entities ... exist in isolation. In a nutshell, using Lambda Expressions we can treat a block of code (functions) as values which can be assigned to a variable....
🌐
YouTube
youtube.com › watch
Java Lambda Expressions #3 - Variable Capture - YouTube
Java Lambda Expressions cannot have their own state, like other classes can. The only way a Java lambda expression can have any kind of internal state is by ...
Published   May 29, 2018
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Lambda and final variables - Java Code Geeks
December 19, 2021 - I am not advocating the creation of lambda expression-based closures in Java, nor the abandonment of the idea. When declaring it, a local variable is final if we use the final keyword. The compiler will also require that the variable get a value only once. This value assignment may happen at the location of the declaration but can be a bit later. There can be multiple lines that assign value to ...