# Sum elements in an sorted List and then add the summed value into list

So, Here is my issue, I have a list which contains something like this [4,7,8,23,41] What I want is 4+7 = 11 so 11 should be added to this list and 4 and 7 should be removed. then 11 +8 = 19 so 19 added and 11 and 8 should be removed.

``````  int finalSum=0;
Collections.sort(myList);

for(int i =0;i<myList.size();i++)
{
for(int j=i+1;i<myList.size();j++)
{
int sum = myList.get(i) + myList.get(j);
myList.remove(i);
myList.remove(j);
}
}

for(int k=0;k<myList.size();k++)
{
finalSum += myList.get(k);
}
``````

I am not sure the reason you would want an algorithm like this, however this should behave the way you have described.

``````public static void main(String[] args) {
Collections.sort(myList);
while (myList.size() > 1) {
}
int finalSum = myList.get(0);
System.out.println(finalSum);
}
``````

A better approach for summing elements in a list would be:

``````public static void main(String[] args) {
List<Integer> myList = Arrays.asList(4,7,8,23,41);
int finalSum = myList.stream().reduce(0, Integer::sum);
System.out.println(finalSum);
}
``````

If you just want to get a final total of the list, You can do it via iterating the whole list and adding each value at the same time.

``````for(int k=0;k<myList.size();k++)
{
finalSum += myList.get(k);
}
``````

But, as you described that you want to add first two numbers from the list and then it should remove them, add the total back to the list and do the same process then we can use PriorityQueue here. It can help to keep track of ascending order and anyways the time complexity for our code will be O(n logn) where n is the size of the list.

``````    PriorityQueue<Integer> pq= new PriorityQueue<>(); // by default it maintains the ascending order
for(int k=0;k<myList.size();k++){
}
while(pq.size()>1){
int num1 = pq.poll(); // taking out first smallest number
int num2 = pq.poll(); // taking out second smallest number
}
finalSum = pq.poll(); // final sum
``````

Since you keep removing elements from the list, you can continue to use index 0.

``````      List<Integer> list = new ArrayList<>(Arrays.asList(4,7,8,23,41));

int first = 0;
while (list.size() > 0) {
int v = list.remove(0) + first;
``````      int sum = list.stream().mapToInt(a -> a).sum();