Hello. It's Kecho. ** Do you guys use stream? ** ** I learned a few days ago and I'm really into it. I'm playing around with it during work. This time I will output FizzBuzz using stream.
IntStream.range(1,101);
The reason for range, not rangeClosed, was conscious of shortcodes. (Finally not so short)
IntStream.range(1,101).mapToObj(i->i%3==0&&i%5==0?"FizzBuzz":i%3==0?"Fizz":i%5==0?"Buzz":i).forEach(i->System.out.println(i));
Yes, it's hard to write, and I'm sure everyone is hard.
i->i%3==0&&i%5==0?"FizzBuzz":i%3==0?"Fizz":i%5==0?"Buzz":i
FizzBuzz is implemented in this part. It is converted to a character string in the following order with the ternary operator.
Output result
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
・ ・ ・
It's good.
Currently it is 129 bytes, but it can be shortened a little.
You can omit the argument by using a method reference.
i->System.out.println(i)System.out::It can be written as println.
```java
IntStream.range(1,101).mapToObj(i->(i%3==0&&i%5==0)?"FizzBuzz":i%3==0?"Fizz":i%5==0?"Buzz":i).forEach(System.out::println);
This is 124 bytes
That is one character shorter.
IntStream.range(1,101).mapToObj(i->(i%3>0&&i%5>0)?i:i%3>0?"Buzz":i%5>0?"Fizz":"FizzBuzz").forEach(System.out::println);
This is 120 bytes. ** We are looking for ways to make it even shorter **
stream fun
He wrote a shorter code in the comments section.
IntStream.range(1,101).forEach(i->System.out.println((i%3<1?"Fizz":"")+(i%5<1?"Buzz":i%3<1?"":i)));
Removes string redundancy in FizzBuzz. Output as it is without using mapToObj. What a 100 byte !!
Recommended Posts