Search code examples
javajava-streamperfect-numbers

What does this line of Java stream mean?


So I have this line of code. It gives me output [6,28]. Do you guys know why? I dont know what kind of numbers was someone trying to print.

System.out.println( IntStream.range(1,30).filter(n -> IntStream.range(1,n).filter(i->n%i == 0).sum() ==n)
               .boxed().collect(Collectors.toList()));

Solution

  • IntStream.range(1,n).filter(i -> n % i == 0).sum() == n
    

    calculates all the divisors of n by checking if n divided by the potential divisor has no remainder (i -> n % i == 0). All divisors are then summed and compared with n itself.

    IntStream.range(1,30).filter(n -> ...).boxed().collect(Collectors.toList())
    

    Just does what I described above for the numbers between 1 and 30 and only keeps those where the comparison is true. It therefore calculates all the numbers between 1 and 30 where the divisors sum to the number itself. Those are called perfect numbers. The first two are 6 and 28, followed by 496, ...