#How to initialize different days using a for loop

1 messages · Page 1 of 1 (latest)

dreamy quartz
#

I am making a medicine tracker as a personal project and wanted to make nodes based off the days of the week. I was trying to see if I can initialize them in a for loop. Is that possible without hard coding the name of the Node?

cyan acornBOT
#

<@&987246399047479336> please have a look, thanks.

main badger
#

You can use streams here!

#

not sure if you're familiar with these, but:

var nodes = Arrays.stream(array)
                .map(element -> new Node(false, element))
                .toArray(Node[]::new);;
#

@dreamy quartz

dreamy quartz
#

I never learned about streams but I have seen them on some other projects. How do they work?

main badger
#
  1. Arrays.stream(array)
  • Creates a stream of the array elements
  1. .map(element -> new Node(false, element))
  • The map method is used to "translate" or "convert" from one type to another. This will be applied for each of the elements.
  • "Take each element of the array and make make new Node out of it
  1. .toArray(Node[]::new)
  • Converts back to the array of the target type - in your case, array of Nodes
#

its just a fluent way to make chaining operations which would otherwise require a loop

#

if you use intellij, it can sometimes translate it back to the loop version!

dreamy quartz
#

Okay tysm!!!

main badger
#

definitely powerful feature of JDK, highly recommended to learn

stable spear
orchid rain
swift mesa
#

If you are familiar with using enums, you can create the initial array using the below method:

DayOfWeek[] days = DayOfWeek.values();

If not, pls follow the solution provided by @main badger.

stable spear
#

(best to understand the solution first before using it)