#How to initialize different days using a for loop
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
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
I never learned about streams but I have seen them on some other projects. How do they work?
Arrays.stream(array)
- Creates a stream of the array elements
.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 Nodeout of it
.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!
Okay tysm!!!
definitely powerful feature of JDK, highly recommended to learn
btw a stream is generally just
A sequence of elements
Please don't teach stream if they struggle with loops 🤦
@dreamy quartz make an array of nodes
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.
(best to understand the solution first before using it)