Print a Heart Shape in Java with a Single Stream Expression
This article demonstrates how to generate a heart‑shaped pattern directly in the console using a concise Java one‑liner that leverages IntStream ranges, mathematical formulas, and conditional character selection, providing the complete code and a visual result.
This short tutorial shows how to create a heart‑shaped output in a Java console using only one line of code powered by the Stream API. The approach combines two nested IntStream ranges, a mathematical equation that defines the heart curve, and conditional logic to print either a character from the word "love" or a space.
IntStream.range(-15, 15)
.map(y -> -y)
.forEach(y -> IntStream.range(-30, 30).forEach(x -> System.out.print(
Math.pow(Math.pow(x * 0.05, 2) + Math.pow(y * 0.1, 2) - 1, 3)
- Math.pow(x * 0.05, 2) * Math.pow(y * 0.1, 3) <= 0
? "love".charAt(Math.abs((y - x) % 4))
: " " + (x == 29 ? "
" : "")
)));The expression works as follows:
Outer stream : IntStream.range(-15, 15).map(y -> -y) iterates over the vertical coordinate y from 15 down to -15.
Inner stream : For each y, IntStream.range(-30, 30) iterates over the horizontal coordinate x from -30 to 29.
Heart formula : The condition
Math.pow(Math.pow(x * 0.05, 2) + Math.pow(y * 0.1, 2) - 1, 3) - Math.pow(x * 0.05, 2) * Math.pow(y * 0.1, 3) <= 0evaluates whether the point ( x, y) lies inside the heart shape.
Character selection : If the point is inside the shape, a character from the string "love" is chosen based on Math.abs((y - x) % 4), creating a patterned fill. Otherwise a space is printed, and a newline is added at the end of each line when x == 29.
Running the program prints a heart made of the letters l, o, v, e in the console, as shown in the accompanying image.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
