Search code examples
javacompiler-errorsjava-streamfunctional-interface

Java Stream API: IntStream to Map


The task is to generate a Map, with keys, represented as integers in the range from 0 to 10, and values, represented as a string value, contcatenated with key-value.

For example,{ key = 1, value = "client_1"; key = 2, value = "client_2" .... }

I tried to do this as shown below:

Map<Integer, String> clients = IntStream.range(1, 10).collect(Collectors.toMap(Function.identity(), new Function<Integer, String>() {
        @Override
        public String apply(Integer integer) {
            return new StringBuilder().append("client_").append(integer).toString();
        }
    }));

And in lambda:

 Map<Integer, String> clients = IntStream.range(1, 10).collect(Collectors.toMap(Function.identity(),
            integer -> new StringBuilder().append("client_").append(integer).toString()));

But IDEA marks this with error and informs, that required type is Supplier<R and provided: Collector<Integer,capture of ?,java.util.Map<java.lang.Object,java.lang.String>>

Collectors.toMap has the following signature:

  toMap(Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper)

I passed into this method arguments with Function-type. Why the Supplier is required?


Solution

  • An IntStream produces a stream of ints, not java.lang.Integers, and hence the compiler error. One solution is to box the steam to convert them to Integers:

    Map<Integer, String> clients = 
        IntStream.range(1, 10).
                 .boxed() // Here!
                 .collect(
                      Collectors.toMap(Function.identity(),
                      i-> new StringBuilder().append("client_").append(i).toString()));