The best solution if the sum of the elements exists in an Array List (Java) – IT Blog
IT Blog
Boris IT Expert

# The best solution if the sum of the elements exists in an Array List (Java)

Boris~November 9, 2020 /Array List

How to check if the sum exists in an Array List in Java. The sum of what elements equal to the needed value in the Array List (Java)? One of the most commonly asked problems on the technical interview. The basic idea here is to start two loops and check if the sum of the element in loop one and the element in loop two is equal to the needed value.

## How to find the sum exists in an ArrayList. Find elements that sum gives needed value in the Array List (Java)?

Detailed implementation.The most apparent solution below:

• Start two loops—one inside the other;
``````//Start first loop
for (int i = 0; i < array.length; i++) {
//Loop to compare with the first item
for (int j = i + 1; j < array.length; j++) ``````
• On each iteration, add numbers from both loops. Check if the result is equal to the needed value. If the check returns true, means we have found two needed elements; (I did not make a draw for each iteration. This is the final iteration with the result)
``````//If first item plus second item equals needed value print the result
if (i + j == sum) {
Log.d("arrayList", "result -> " + i + " " + j);
}``````

Full code solution:

`````` private void checkIfSumOfItemsEqualToNeededValue() {
//Creating new array
int[] array = new int[]{1, 2, 3, 4, 5};

//Expected sum value
int sum = 8;

//Start first loop
for (int i = 0; i < array.length; i++) {
//Loop to compare with the first item
for (int j = i + 1; j < array.length; j++) {
//If first item plus second item equals needed value print the result
if (i + j == sum) {
Log.d("arrayList", "result -> " + i + " " + j);
}
}
}

}``````

In this article, I show you the solution to check if sum exists in array list (Java).

Full code and more examples in my facebook group.