Java遍历BSON Document报错:Lambda表达式参数不匹配求助
Ah, I get it, let's break down why you're hitting this error with MongoDB's Document.forEach() method.
First, let's clarify what's happening under the hood: MongoDB's Document class implements Java's Map<String, Object> interface. That means its forEach method uses the Map interface's version, which expects a BiConsumer functional interface—this requires two parameters: the document's key (a String) and its corresponding value (an Object).
Why your first code failed
Your initial lambda only passed one parameter:
new Document().append("test",1).forEach(record -> { System.out.println(record); })
The compiler immediately flags this because it's looking for a lambda that takes two arguments (key and value), but you only provided one. That's exactly what the error expected parameter 2 but found 1 is telling you.
Why your second attempt didn't work
When you tried adding a second parameter, you messed up the lambda syntax! For lambdas with multiple parameters, you must wrap the parameters in parentheses. Your code:
new Document().append("test",1).forEach(record, param2 -> {
...is invalid syntax. The compiler doesn't recognize record, param2 as a valid parameter list without parentheses around them.
The correct implementation
Here's how to fix it properly—use parentheses for the two parameters, and you can use them to access both the key and value of each entry in the Document:
new Document().append("test", 1).forEach((key, value) -> { System.out.println("Key: " + key + ", Value: " + value); });
If you only care about one of the parameters (say, just the value), you can still include both parameters and ignore the one you don't need—though it's good practice to name unused parameters with an underscore to make that clear:
new Document().append("test", 1).forEach((_key, value) -> { System.out.println("Value: " + value); });
内容的提问来源于stack exchange,提问作者Maaz Soan

