1

I am trying to create a Map, where keys run value from 1 to N, and values are some constant for each of these kesys-

 private Map<Integer, Integer> getInitialDistMap(int N) {
    Function<Integer, Integer> constant = x -> Integer.MAX_VALUE;
    return IntStream.rangeClosed(1, N).collect(Collectors.toMap(Function.identity(), constant));
}

This construct is giving me error.

2 Answers2

1

IntStream.rangeClosed() returns an IntStream and not a Stream<Integer>. An IntStream is a primitive Stream of ints. To transform an IntStream to a Stream<Integer> you need to call IntStream.boxed() on your stream:

private Map<Integer, Integer> getInitialDistMap(int N) {
    Function<Integer, Integer> constant = x -> Integer.MAX_VALUE;
    return IntStream.rangeClosed(1, N).boxed()
            .collect(Collectors.toMap(Function.identity(), constant));
}
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
1

static IntStream rangeClosed(int startInclusive,int endInclusive)

rangeClosed will return the IntStream and the only collect method available on IntStream is

<R> R collect(Supplier<R> supplier,ObjIntConsumer<R> accumulator, BiConsumer<R,R> combiner)

So use boxed() which returns Stream<Integers> stream of Integers and then collect to Map

Stream<Integer> boxed()

Returns a Stream consisting of the elements of this stream, each boxed to an Integer.

Solution

IntStream.rangeClosed(1, N).boxed().collect(Collectors.toMap(Function.identity(), constant));
Community
  • 1
  • 1
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98