1

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
theAsker
  • 527
  • 3
  • 14
  • remove the braces `{}` in value mapping – Naman Nov 20 '19 at 11:45
  • Possible duplicate [What is the breakdown for Java's lambda syntax?](https://stackoverflow.com/questions/25192108/what-is-the-breakdown-for-javas-lambda-syntax/25197679) – Naman Nov 20 '19 at 11:48

1 Answers1

2

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    But as a side note, `Map.ofEntries(Map.entry(a, b))` is a verbose version of `Map.of(a, b)`. – Holger Nov 20 '19 at 12:43