[JAVA] Output FizzBuzz with stream

Introduction

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.

Try

Anyway, generate from 1 to 100

IntStream.range(1,101);

The reason for range, not rangeClosed, was conscious of shortcodes. (Finally not so short)

Create FizzBuzz using mapToObj

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.

  1. Convert to FizzBuzz if divisible by 3 or 5
  2. Convert to Fizz if divisible by 3 3.5 Convert to Buzz if divisible by 5
  3. As it is

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.

Try to shorten

Currently it is 129 bytes, but it can be shortened a little.

Use method references

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

Write == with>

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 **

Summary

stream fun

Postscript

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

Output FizzBuzz with stream
Output multiplication table with Stream
csv file output with opencsv
CSV output with Apache Commons CSV
Control log output with Doma2
Output "Izumi Oishi" with dokojava
Output Excel with formulas with XlsMapper
Output characters like conversation with JavaFX
Output test coverage with clover + gradle
[Java] Element existence check with Stream
Output PDF and TIFF with Java 8
Java8 list conversion with Stream map
Output system time to MANIFEST.MF with Maven
Implement image input / output with Spring MVC