shirohoo
shirohoo

Reputation: 91

How should i get result used stream in Java?

here a string[]

String[] strings = {"3", "1", "4", "3", "2"};

i want to change this to a number then sort and cumulative operations

  1. change number
int[] ints = {3, 1, 4, 3, 2};
  1. sort
int[] ints = {1, 2, 3, 3, 4};
  1. cumulative operations
1           =    1
1+2         =    3
1+2+3       =    6 
1+2+3+3     =    9
1+2+3+3+4   =   13

result      =   1+3+6+9+13  = 32
int[] ints = {1, 2, 3, 3, 4};

int result = 0;

for(int i = 0; i < 5; i++) {
    int sum = 0;
        for(int j = 0; j <= i; j++) {
            sum += ints[j];
        }
    result += sum;
}
result = 32

finally, i want to change this code to stream.

i have tried to:

String[] strings = {"3", "1", "4", "3", "2"};
            
int asInt = stream(strings)
                .mapToInt(Integer::parseInt)
                .sorted()
                .reduce(Integer::sum)
                .getAsInt();
asInt = 13

what should I do to get the result i want?

Upvotes: 1

Views: 173

Answers (3)

String[] strings = {"3", "1", "4", "3", "2"};
AtomicInteger ai = new AtomicInteger();

Arrays.stream(strings)
      .mapToInt(Integer::parseInt)
      .sorted()
      .map(ai::addAndGet).sum();  // returns 32

Upvotes: 2

Most Noble Rabbit
Most Noble Rabbit

Reputation: 2776

A declartive, straightforward solution:

  1. Map and sort the array.
  2. Create an IntStream of 1 to array's length and sum the first i elements sum each time.

Code:

String[] strings = {"3", "1", "4", "3", "2"};

int[] ints = Arrays.stream(strings)
        .mapToInt(Integer::parseInt)
        .sorted()
        .toArray();

int cumulativeSum = IntStream.rangeClosed(1, ints.length)
        .map(i -> Arrays.stream(ints)
                .limit(i)
                .sum())
        .sum();

Output:

32

Upvotes: 1

BeUndead
BeUndead

Reputation: 3628

There's almost certainly a better approach, but as a quick solution until someone gives a better one:

final int[] index = {strings.length};
final int result = Arrays.stream(strings)
                         .mapToInt(Integer::parseInt)
                         .sorted()
                         .reduce(0, (a, b) -> a + (index[0]-- * b));

The idea here being that your desired number counts the first number 5 times, the second one 4 times, the third one 3 times, etc.

Using a final int[] as basically a variable that can be used in the stream (must be final). index[0]-- on each step to ensure the next one is multiplied by less.

Upvotes: 1

Related Questions