nus-cs2030 / 2021-s2

2 stars 2 forks source link

1819SEM1 Question 3 #397

Open Zhiaowei99 opened 3 years ago

Zhiaowei99 commented 3 years ago

Summary

I have trouble using the stream method. I can't figure out why. Can anyone help me? :))

Description

Post the question that you would like your peers or seniors to answer.

Suggested Answer (if any):

Screenshot 2021-04-28 at 12 13 15 AM

Screenshots (if any):

Screenshot 2021-04-28 at 12 11 35 AM
ShyamalSankar commented 3 years ago

Once you process the stream it is gone. Ie if you find the max you cannot use the stream again to find the minimum.

I suggest converting every element of the IntStream to an instance of the minMax class. Like so: instream.map(x -> new MinMax(x,x)).reduce(lambda)

Inside your lambda you should extract the min of x and the min of y and compare them and get the minimum between the 2. Do the same for the max and then create a new min max instance and return it. Hope this helps!

eseutella commented 3 years ago

Hello here's my attempt. I map each element in the stream to a new MinMax(element, element) and then I use reduce to get the maximum and minimum values. Hope this helps!

Screenshot 2021-04-28 001853
Jeyxiang commented 3 years ago

Hi you can only operate on the stream once. Meaning to say instream can only be used once, so after calling a terminal operation on a stream (max() in this case), you cannot use the same stream again. You can check out this link for a clearer explanation.

Jjjetplane commented 3 years ago

Streams can only be used once, once consumed if cannot be reused.

seanangwj commented 3 years ago

As what is already mentioned above, the stream has been operated on and to solve this question, you can try using reduce instead.

markwty commented 3 years ago

You can also consider using IntSummaryStatistics image and then retrieve the maximum and minimum.

chooweixiang98 commented 3 years ago

image