user7889665
user7889665

Reputation:

Transform this into method that uses streams?

Do you know how should I transform this :

private static Map<Integer, EmptyTile> createAllPossibleEmpyTiles() {
 Map<Integer,EmptyTile> emptyTileMap = new HashMap<Integer, EmptyTile>();
        for (int i = 0; i <64 ; i++) {
            emptyTileMap.put(i,new EmptyTile(i));
        }
        return emptyTileMap;
}

?

Upvotes: 1

Views: 57

Answers (2)

Mansur
Mansur

Reputation: 1829

So, let's examine the traditional way and try to convert it into the stream format.

Map<Integer, EmptyTile> emptyTileMap = new HashMap<>();
for (int i = 0; i < 64; i++) {
    emptyTileMap.put(i, new EmptyTile(i));
}
return emptyTileMap;

There's a couple of things going on here.

  1. We explicitly loop through the interval of [0, 64)
  2. We generate tile objects based on the values of the interval
  3. We maintain a map to keep all the generated tile objects

So, we can start the conversion from the very first part - the explicit loop. This can be achieved using IntStream.range(start, end) function.

Next up, we will generate the tile objects based on the interval values, so:

IntStream.range(0, 64)
        .mapToObj(number -> new EmptyTile(number))

We can use method reference here to shorten the code:

IntStream.range(0, 64)
        .mapToObj(EmptyTile::new)

Next, we need to add those values to the map. To do this, we need toMap collector. It accepts a key mapper and a value mapper (it has 2 more forms). Our key will be the generated number, and the value is the object itself, so, this is the final look.

private Map<Integer, EmptyTile> createAllPossibleEmptyTilesStream() {
    return IntStream.range(0, 64)
            .mapToObj(EmptyTile::new)
            .collect(toMap(EmptyTile::getValue, x -> x));
}

Here, x -> x is the identity function. The value mapper is a function which accepts an EmptyTile object and returns something else. Since we need the value to be object itself, we just return it.

Upvotes: 2

nano_nano
nano_nano

Reputation: 12523

one possibility to do this:

Map<Integer, EmptyTile> emptyTileMap = IntStream.range(0, 64).boxed().collect(toMap(i -> i, EmptyTile::new));

Upvotes: 1

Related Questions