Print a Heart Shape in the Console with a One‑Liner Java Stream

This short tutorial shows how to use Java's IntStream API to generate an ASCII heart directly in the console with a single expressive one‑line statement, complete with the full code snippet and a visual result.

FunTester
FunTester
FunTester
Print a Heart Shape in the Console with a One‑Liner Java Stream

Inspired by a Python one‑liner that prints a heart shape, this article demonstrates that the same effect can be achieved in Java using the Stream API. The author provides a compact, functional‑style code example that leverages IntStream.range, map, and nested forEach calls to compute and print each character.

Code Example

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 evaluates a mathematical formula that defines the heart shape. For each coordinate (x, y) within the defined ranges, it checks whether the point satisfies the heart equation; if it does, a character from the word "love" is printed, otherwise a space is printed. A newline is added at the end of each line.

Result

The output displays a recognizable heart shape made of the characters from the word "love", illustrating how concise functional Java code can produce complex ASCII art.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaprogrammingStreamsconsoleASCII artHeart Shape
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.