2

Can the below while loop be converted to IntStream?

Here modifiedNumber is an int. I want to refactor this to java8.

while (modifiedNumber > 0) {
    tempNumber = (int) ((modifiedNumber % 10) * Math.pow(10, count));
    alist.add(tempNumber);
    modifiedNumber = modifiedNumber / 10;
    count++;
}
GhostCat
  • 137,827
  • 25
  • 176
  • 248
user3310115
  • 1,372
  • 2
  • 18
  • 48
  • Could you add to the question, what exactly are you trying to do with the code above? Are you trying to reverse a number> – Naman Sep 02 '17 at 04:55
  • No I'm trying just split the numbers by decimal values. So like 123 is 3, 20,100 – user3310115 Sep 02 '17 at 05:20

2 Answers2

0

Well, not very sure of the declarations used for the variables used in your code shared, but to transform the above code to use IntStream, you can attempt something like(declarations mine) :

final int[] modifiedNumber = {123};
final int len = String.valueOf(modifiedNumber[0]).length();
ArrayList<Integer> aList = new ArrayList<>();
final int[] count = {0};
IntStream.range(0,len).forEach(mn -> {
    double pow = Math.pow(10, count[0]);
    int tempNumber = (int) ((modifiedNumber[0] % 10) * pow);
    aList.add(tempNumber);
    modifiedNumber[0] = modifiedNumber[0] / 10;
    count[0]++;
});

System.out.println(aList);

Note: Most of the integer values are converted to final single valued array to be consumed within the streams.

Naman
  • 27,789
  • 26
  • 218
  • 353
  • So based on this, does using streams here make any sense in this case? – user3310115 Sep 02 '17 at 06:37
  • @user3310115 the effectiveness of using streams is mostly when you want to execute oprations in parrallel. Good read over forEach vs for each : - https://stackoverflow.com/a/16635489/1746118 – Naman Sep 02 '17 at 07:04
0

Here is a possible way to do it. You could also pass multiple numbers to Stream.of() and the output will be a stream of the dissection of all those numbers.

final Stream< Integer > integerStream = Stream.of( modifiedNumber ).flatMap( n -> {
    final List< Integer > aList = new LinkedList<>();

    int tempNumber, count = 0;

    while ( n > 0 ) {
        tempNumber = ( int ) ( ( n % 10 ) * Math.pow( 10, count ) );
        aList.add( tempNumber );
        n = n / 10;
        count++;
    }

    return aList.stream();
} );
alirabiee
  • 1,286
  • 7
  • 14