Reputation: 91
here a string[]
String[] strings = {"3", "1", "4", "3", "2"};
i want to change this to a number then sort and cumulative operations
int[] ints = {3, 1, 4, 3, 2};
int[] ints = {1, 2, 3, 3, 4};
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
Reputation: 1097
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
Reputation: 2776
A declartive, straightforward solution:
Map
and sort
the array.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
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