Search code examples
javalistjava-8uniqueperfect-square

How to print Unique Squares Of Numbers In Java 8?


Here is my code to find the unique number and print the squares of it. How can I convert this code to java8 as it will be better to stream API?

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
HashSet<Integer> uniqueValues = new HashSet<>(numbers);

for (Integer value : uniqueValues) {
    System.out.println(value + "\t" + (int)Math.pow(value, 2));
}

Solution

  • Use IntStream.of with distinct and forEach:

    IntStream.of(3, 2, 2, 3, 7, 3, 5)
             .distinct()
             .forEach(n -> System.out.println(n + "\t" +(int)Math.pow(n, 2)));
    

    or if you want the source to remain as a List<Integer> then you can do as follows:

    numbers.stream()
           .distinct()
           .forEach(n -> System.out.println(n + "\t" +(int)Math.pow(n, 2)));
    

    yet another variant:

    new HashSet<>(numbers).forEach(n -> System.out.println(n + "\t" +(int)Math.pow(n, 2)));