Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 11661

Strange Compiler Error with Collectors.toMap() : reference to method is ambiguous, both Map and List match

$
0
0

This class doesn't compile (using javac 17 or 21), because the second invocation of set() is allegedly ambiguous, while the first one is OK:

import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.stream.Collectors;public class ListVsMap {    public static void main(String[] args) {        set(List.of("foo", "bar", "baz")                .stream()                .collect(Collectors.toMap(                        l -> l,                        l -> l,                        (x, y) -> y)));        set(List.of("foo", "bar", "baz")                .stream()                .collect(Collectors.toMap(                        l -> l,                        l -> l,                        (x, y) -> y,                        HashMap::new)));    }    public static void set(Map<String, String> valueMap) {}    public static void set(List<String> values) {}}

The error message is

ListVsMap.java:17: error: reference to set is ambiguous        set(List.of("foo", "bar", "baz")        ^  both method set(Map<String,String>) in ListVsMap and method set(List<String>) in ListVsMap match1 error

I don't understand this error.

The only difference between both invocations is the Supplier HashMap::new in Collectors.toMap().

But the first version of toMap() actually calls the second one internally, and both declarations seem identical, except for some variation in the generics.

List and Map are distinct types, so type erasure can't be the reason that the compiler can't choose the correct method.

Is it a bug in javac?


Viewing all articles
Browse latest Browse all 11661

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>