Java Program to Replace Each Array Element with the Sum of All Other Elements

In this Java program, we will learn how to transform an array so that each element is replaced by the sum of all the other elements.

For example:

Input  : {10, 20, 30, 40}
Output : {90, 80, 70, 60}

How does it work?

For each element, we calculate the total sum of the array and subtract the current element.

Total = 10 + 20 + 30 + 40 = 100

100 - 10 = 90
100 - 20 = 80
100 - 30 = 70
100 - 40 = 60

1. Traditional Java Program Using for Loop

public class ArraySumExceptElement {

    public static void main(String[] args) {

        int[] arr = {10, 20, 30, 40};
        int[] result = new int[arr.length];

        int sum = 0;

        // Calculate the total sum
        for (int i = 0; i < arr.length; i++) {
            sum = sum + arr[i];
        }

        // Subtract each element from total sum
        for (int i = 0; i < arr.length; i++) {
            result[i] = sum - arr[i];
        }

        System.out.print("Output: {");

        for (int i = 0; i < result.length; i++) {
            System.out.print(result[i]);

            if (i < result.length - 1) {
                System.out.print(", ");
            }
        }

        System.out.println("}");
    }
}

Output

Output: {90, 80, 70, 60}

Explanation

First, we calculate the sum of all array elements:

int sum = 0;

for (int i = 0; i < arr.length; i++) {
    sum = sum + arr[i];
}

For the input array:

{10, 20, 30, 40}

the total sum is:

100

Then we subtract each element from the total sum:

result[i] = sum - arr[i];

Therefore:

100 - 10 = 90
100 - 20 = 80
100 - 30 = 70
100 - 40 = 60

The final result is:

{90, 80, 70, 60}

2. Java 8 Program Using Stream API

Java 8 provides the Stream API, which can be used to calculate the total sum and transform each array element.

import java.util.Arrays;

public class ArraySumExceptElementJava8 {

    public static void main(String[] args) {

        int[] arr = {10, 20, 30, 40};

        int sum = Arrays.stream(arr).sum();

        int[] result = Arrays.stream(arr)
                .map(n -> sum - n)
                .toArray();

        System.out.println("Output: " + Arrays.toString(result));
    }
}

Output

Output: [90, 80, 70, 60]

Explanation of Java 8 Program

The following statement calculates the sum of all elements:

int sum = Arrays.stream(arr).sum();

For the given array:

{10, 20, 30, 40}

the sum is 100.

The map() method then subtracts each element from the total:

.map(n -> sum - n)

Here, n -> is a Java 8 lambda expression.

The resulting stream is converted back into an array using:

.toArray();

Finally, Arrays.toString() displays the result.


Comparison of Both Methods

FeatureTraditional JavaJava 8
Approachfor loopStream API
Lambda expressionNoYes
Stream APINoYes
Easy for beginnersYesModerate
Code lengthLongerShorter
Java VersionAll common versionsJava 8+

Which Method Should You Use?

  • For beginners: Use the for loop method because it clearly explains the logic.
  • For Java 8 learning: Use the Stream API version.
  • For interviews: Understand both approaches and the time complexity.

Time Complexity

Both approaches take O(n) time because the array needs to be processed.

The traditional approach uses an additional result array, so the extra space complexity is O(n).

Conclusion

This Java program demonstrates how to replace every array element with the sum of all other elements. The traditional for loop approach is easy to understand, while the Java 8 Stream API provides a concise functional programming solution.

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *