I will kick start with my question:
I have an array:
int[] arr = { 1,2,3,4,5 };
, i want to store values to a List<Integer> li
like this : 14,13,12,11,10
How these values came to the List li
like this??
Our initial numbers are 1,2 ,3 ,4 , and 5 . We can calculate the following sums using four of the five integers:
- If we sum everything except 1, our sum is 14.
- If we sum everything except 2, our sum is 13.
- If we sum everything except 3, our sum is 12.
- If we sum everything except 4, our sum is 11.
- If we sum everything except 5, our sum is 10.
My approach and thoughts:
I thought i already have an int [] arr
, so i will make it to stream , now i will filter
out each elements one by one and will sum
rest in each iteration and will add this to List li
.
List<Integer> li = IntStream.range(0,1).filter(i-> arr[i] !=i).sum();
^^ This did not worked, I am thinking can i do some this like below?
IntStream.range(0,1).filter(i-> filter(this is anotherfilter)).sum();
I am not able to understand this, i want to do this problem with streams and java-8.
You can break it into two steps and perform the operation as:
int[] arr = { 1,2,3,4,5 };
int total = Arrays.stream(arr).sum(); // total of the array
List<Integer> output = Arrays.stream(arr)
.mapToObj(integer -> total - integer) // (total - current) value as element
.collect(Collectors.toList());