I'm new to java and would like to know how I could convert the following code from using a HashMap called floorsMap to using an ArrayList called floorsArray instead.
void randomizeQueues(String flag) {
double num = (flag.equals("enforce")) ? 0.99 : Math.random();
if (num > 0.5)
floorsMap.values().forEach(Floor::randomizeDestinations);
}
forEach is a terminal operation; it returns nothing; calling a method that has no side effects is therefore a do-nothing operation.
I think you're looking for a series of operations that convert and then roll the results into a new collection type. The stream API is used to do this:
List<Floor> randomizedFloors = floorsMap.values().stream()
.map(Floor::randomizeDestinations)
.collect(Collectors.toList());
EDIT:
Perhaps randomizeDestinations randomizes 'in place' and returns void. In that case you can't keep the map intact and then have a list with randomized destinations unless you have a way to clone the Floor object, which you'd have to explicitly make. You could do:
List<Floor> randomizedFloors = floorsMap.values().stream().map(floor -> {
Floor clone = floor.makeACopy(); // you must write this
clone.randomizeDestinations();
return clone;
}).collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With