Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of code from a HashMap to an ArrayList

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);
}
like image 277
newToBeingNerdy Avatar asked Nov 29 '25 00:11

newToBeingNerdy


1 Answers

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());
like image 188
rzwitserloot Avatar answered Nov 30 '25 12:11

rzwitserloot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!