Cannot infer type argument(s) for map(function)

The error “cannot infer type argument(s) for map(function)” occurs when the compiler is unable to determine or infer the type argument for the map() function.

In the context of Java’s Stream API, the map() function is used to transform each element of a stream into another object. It takes a Function as an argument, which defines the transformation to be applied.

The error message suggests that the compiler is having trouble figuring out the types involved in the map() function’s signature. To resolve this error, you need to provide explicit type arguments to the map() function.

Let’s look at an example to understand this error in more detail:


List<String> words = Arrays.asList("apple", "banana", "cherry");

List<Integer> lengths = words.stream()
                               .map(String::length)
                               .collect(Collectors.toList());
  

In the above example, we have a list of strings. We want to transform each string into its respective length and collect the lengths into a new list. However, if you try to compile this code, you will get the “cannot infer type argument(s)” error.

To fix this error, we need to provide the type arguments explicitly:


List<Integer> lengths = words.stream()
                               .map<String, Integer>(String::length)
                               .collect(Collectors.toList());
  

By specifying the types <String, Integer> for the map() function, we explicitly tell the compiler that we are transforming strings into integers. This resolves the error, and the code will now compile successfully.

Read more interesting post

Leave a comment