Search code examples
javahashmapjava-streamcollectors

How do I fill a HashMap<Long, Long> using a Stream in Java


I want to fill a HashMap<Long, Long> using a Stream in Java. However, I am not getting it right. I hope someone can help.

I was thinking along these lines:

HashMap<Long, Long>  mapLongs = LongStream
    .rangeClosed(1, 10)
    .collect(Collectors.toMap(x -> x, x -> getSquare(x)));

where getSquare is a simple function that returns the square, e.g.:

long getSquare(long x) {
    return x * x;
}

However, I get an error saying that getSquare() cannot be applied to an Object. When I try to cast x to an object, I get an error that:

no instance(s) of type variable(s) A, K, T, U exist so that Collector> conforms to Supplier

Bottom line: I am stuck.

Also (obviously), I am trying to do something more complex than filling a Map with square values...


Solution

  • Just make sure your stream is boxed.

    Map<Long, Long> mapLongs = LongStream  // programming to interface 'Map'
            .rangeClosed(1, 10)
            .boxed()
            .collect(Collectors.toMap(x -> x, x -> getSquare(x))); // can use method reference as well