Issue
I recently stumbled across the following issue.
Basically I have a set of pairs which i want to transform to a map of maps . Below is the code snippet:
Set<Map.Entry<String,String> > testSet = new HashSet<>(
Arrays.asList(
entry("key1","value1"),
entry("key1","value1")
)
);
Map<String,Map<String,String>> testMap = testSet
.stream()
.collect(
Collectors.toMap(
entry -> entry.getKey(),
entry-> {
Map.ofEntries(
entry(entry.getKey(),entry.getValue() + "2")
);
}
)
);
The above snippet does not compile because the functions that are passed to the toMap expect Objects and not Map.Entry objects, so the compiler cannot find the methods specific to the Map.Entry.
I have no idea why this happens so any help is appreciated.
Solution
It should be:
Map<String,Map<String,String>> testMap = testSet
.stream()
.collect(
Collectors.toMap(
entry -> entry.getKey(),
entry -> Map.ofEntries(entry(entry.getKey(),entry.getValue() + "2"))
)
);
When you are using a lambda expression body with curly braces, it must contain a return statement (assuming the corresponding functional interface's method has a return value).
If the lambda expression's body is just a single expression, it doesn't have to be wrapped in braces.
Answered By - Eran
Answer Checked By - Marilyn (JavaFixing Volunteer)