Pythagorean Triplet using Java8

Viewed 805

I am trying to find all pythagorean triplets below a given number using Java8.

I tried to solve the problem with the code shown below. But, I am still mutating the triplets list.

I would want to know ways in which the below code can be implemented without mutating the list.

public static List<Triplet> returnPythogoreanTriplets(int num) {
    List<Triplet> triplets = new ArrayList();
    IntStream.rangeClosed(1, num).forEach(hyp->{
        IntStream.range(1, hyp)
          .forEach(side1->{
              IntStream.rangeClosed(1, side1)
                .forEach(side2->{
                    Triplet t = new Triplet<>(side2, side1, hyp);
                    if(t.isPythagorean()){
                        triplets.add(t);
                        System.out.println(t);
                    }
                });
          });
       });
    return triplets;
}
2 Answers

IntStream.rangeClosed(1, 100).boxed().flatMap(a -> IntStream.rangeClosed(a, 100) .filter(b -> Math.sqrt(aa + bb) % 1 == 0) .mapToObj(b -> new int[]{a, b, (int)Math.sqrt(a * a + b * b)}) ).forEach(a->System.out.println(Arrays.toString(a)));

Related