使用Java8的勾股三元组

使用Java8的勾股三元组,java,functional-programming,java-8,Java,Functional Programming,Java 8,我正在尝试使用Java8查找给定数字以下的所有毕达哥拉斯三胞胎 我试图用下面显示的代码解决这个问题。但是,我仍然在改变三胞胎名单 我想知道如何在不改变列表的情况下实现下面的代码 public static List<Triplet> returnPythogoreanTriplets(int num) { List<Triplet> triplets = new ArrayList(); IntStream.rangeClosed(1, num).forE

我正在尝试使用Java8查找给定数字以下的所有毕达哥拉斯三胞胎

我试图用下面显示的代码解决这个问题。但是,我仍然在改变三胞胎名单

我想知道如何在不改变列表的情况下实现下面的代码

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;
}
publicstaticlist返回pythogoreantriplets(int-num){
列表三元组=新的ArrayList();
IntStream.rangeClosed(1,num).forEach(hyp->{
IntStream.range(1,hyp)
.forEach(第1边->{
IntStream.rangeClosed(1,side1)
.forEach(第2边->{
三联体t=新三联体(第2侧、第1侧、hyp);
if(t.isPythagorean()){
三联体。加(t);
系统输出打印ln(t);
}
});
});
});
返回三胞胎;
}

以下操作将完成此操作

public static List<Triplet> returnPythogoreanTriplets(int num) {
    return IntStream.rangeClosed(1, num).boxed().flatMap(hyp -> 
        IntStream.range(1, hyp).boxed().flatMap(side1 -> 
            IntStream.rangeClosed(1, side1).mapToObj(side2 -> new Triplet(side2, side1, hyp))
        )
    )
    .filter(Triplet::isPythagorean)
    .collect(Collectors.toList());
}
顺便说一句,这是一个非常缓慢的蛮力实现,用于构建毕达哥拉斯三胞胎:)。

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

代码总是好的,但它也有助于添加一些注释/上下文,说明如何解决原始问题。
public static void main(String[] args) {
    System.out.println(returnPythogoreanTriplets(3));
    // prints "[Triplet [a=1, b=1, c=2], Triplet [a=1, b=1, c=3], Triplet [a=1, b=2, c=3], Triplet [a=2, b=2, c=3]]"
}