Recursive sum of digits of a number (up to a digit less than 10) java 8 lambdas only

I just practice lamdas java 8. My problem is as follows

Sum all digits in integers until their value is less than 10 (means one digit to the left) and check if it has 1

Input Example 1

100 

Output Example 1

 1 // true because its one 

Input Example 2

 55 

Output Example 2

 1 ie 5+5 = 10 then 1+0 = 1 so true 

I wrote the code

 System.out.println(Arrays.asList( String.valueOf(number).split("") ).stream() .map(Integer::valueOf) .mapToInt(i->i) .sum() == 1); 

It works for input 1, i.e. 100, but not for input 2, i.e. 55, which I clearly understand that in the second case, 10 is the result because the iteration is not recursive.

So, how can I make this lambdas expression recursive so that it can work in the second case too? I can create a method with this lambda expression and call it every time until the return value is <10, but I was wondering if there is any approach in lambdas.

thanks

+6
source share
2 answers

If you want a pure lambda solution, you should forget about its recursiveness, since there is absolutely no reason for implementing an iterative process as recursion:

 Stream.iterate(String.valueOf(number), n -> String.valueOf(n.codePoints().map(Character::getNumericValue).sum())) .filter(s -> s.length()==1) .findFirst().ifPresent(System.out::println); 

Demo

+7
source

Creating recursive lambdas in Java is not easy due to the error "the variable may be uninitialized," but it can be done. Here is a link to the answer that describes one way to do it .

When applied to your task, this can be done as follows:

 // This comes from the answer linked above class Recursive<I> { public I func; } public static void main (String[] args) throws java.lang.Exception { Recursive<Function<Integer,Integer>> sumDigits = new Recursive<>(); sumDigits.func = (Integer number) -> { int s = Arrays.asList( String.valueOf(number).split("") ) .stream() .map(Integer::valueOf) .mapToInt(i->i) .sum(); return s < 10 ? s : sumDigits.func.apply(s); }; System.out.println(sumDigits.func.apply(100) == 1); System.out.println(sumDigits.func.apply(101) == 1); System.out.println(sumDigits.func.apply(55) == 1); System.out.println(sumDigits.func.apply(56) == 1); } 

I took your code, wrapped it in { ... } s, and added a recursive call to the return string.

Demo version

+3
source

All Articles