Java.Java8.How can I display unique squares of numbers using the map() method?

✅ Goal:

  • Square each number in a list.
  • Remove duplicates (make them unique).
  • Print them using forEach().

🔹 Example

import java.util.List;

public class UniqueSquares {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(2, 3, 4, 3, 2, 5);

        numbers.stream()
               .map(n -> n * n)          // square each number
               .distinct()               // remove duplicates
               .forEach(System.out::println); // display
    }
}

🔹 Output:

4
9
16
25

map(n -> n * n): transforms each number to its square.

distinct(): filters out duplicates.

forEach(...): prints the result.

Bonus: Want to sort the unique squares before printing?

Just add .sorted():

.map(n -> n * n)
.distinct()
.sorted()
.forEach(System.out::println);
This entry was posted in Без рубрики. Bookmark the permalink.