nus-cs2030 / 2122-s2

CS2030 repository and wiki for AY 2021/2022 Sem 2
MIT License
0 stars 0 forks source link

gameOfLife( ) - converting stream to string #157

Open lihuicham opened 2 years ago

lihuicham commented 2 years ago

Hi ! I need some help in converting stream to string, so i can replace the element "0" to "" and "1" to "*" i tried to use .collect(Collectors.joining()) and it didnt work because collect is a terminating operator i tried to use .reduce("", (x+y) -> String.valueOf(x) + String.valueOf(y)) and this didnt work as well (it threw me errors)...

anybody can point me in the right direction of converting stream to string ?

kkennyllow commented 2 years ago

if im not wrong, it should be .reduce("", (x, y) -> String.valueOf(x) + String.valueOf(y)) right?

NUST007 commented 2 years ago

how about trying a .map() method for Stream? You could write a helper function<Integer, String> f(Integer i) that does the conversion from Integer to the desired String, then do something like .map(x -> f(x)) to change the stream to " " and "*" directly.

alantay11 commented 2 years ago

mapping a stream of integers (x -> " ") will make it a stream of strings, you can try it out using a test stream in jshell and /var to see what types are created for different functions

loqir commented 2 years ago

you can try using the map function to first convert lists into streams, then within the same map function convert each integer to a string and reduce them to a single string, so each list can be represented by a string

bryankwe commented 2 years ago

I also used .collect(Collectors.joining()) but in a helper function which converted a List<Integer> into a String

Following which, in gameOfLife(), I just mapped each List<Integer> in my stream using that helper function to get the required output

ca-leb commented 2 years ago

to convert a stream to string, first you can do a .map() to convert the stream of ints into a stream of strings, followed by a .reduce() to reduce the stream of strings to a single string. hope this helps!