Java – How to populate HashMapLong, Long using Stream in Java

How to populate HashMap using Stream in Java… here is a solution to the problem.

How to populate HashMap using Stream in Java

I’m going to fill in a HashMap<Long, Long> using Stream in Java. However, I didn’t get it right. I hope someone can help.

I thought so:

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, for example:

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

However, I get an error message stating that getSquare() cannot be applied to objects. When I try to convert x to an object, I get an error:

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

Bottom line: I’m stuck.

Also(obviously) I’m trying to do something more complicated than filling the map with squared 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

Related Problems and Solutions