N-rG N-rG - 5 months ago 15
Java Question

Transform double for Loop to Stream?

I'm just curious if i can switch this

for (String arg : args) {
int number = Integer.parseInt(arg);
int checksum = 0;

for (int digits = 0; digits < 10; digits++) {
checksum += number % 10;
number /= 10;
}
System.out.println(checksum);
}
}


into a piped Java Stream (only that condition, no recursive method etc.).

My first attempt was

public static void main(String... args) {
Stream.of(args)
.?
}


with then somehow use a function like:

class FunctionTest implements Function<String, Integer> {
@Override
public Integer apply(String s) {
int number = Integer.parseInt(s);
int checksum = 0;

IntStream.range(1,10).reduce(number, ()-> ?)

checksum += number % 10;
number /= 10;

return checksum;
}
}


But I guess I come to a dead end with that...

Does someone has a better idea or is it actually impossible?

Answer
Arrays.stream(args)
      .map(Integer::parseInt)
      .map(number -> {
          int sum = 0;
          for(int i = 0; i < 10; i ++) {
              sum += number % 10;
              number /= 10;
          }
          return sum;
      })
      .forEach(System.out::println);

Or alternatively (note this would not work for negative numbers):

Arrays.stream(args)
      .map(number -> number.split(""))
      .map(Arrays::stream)
      .map(strStream -> strStream.mapToInt(Integer::parseInt))
      .map(IntStream::sum)
      .forEach(System.out::println);

This one splits the string into its individual character strings, maps them to integers and then sums them