Java 8 – Find sum of Largest 2 numbers in an Array or List or Stream

In this article, we will discuss what are the different optimum ways to find sum of largest 2 numbers in an Array or List or Stream

1. Finding sum of largest 2 numbers in an Array

  1. Using Stream.sorted().skip() method
  2. Using Stream.sorted(Comparator).limit() method
  3. Before Java 8 release

1.1 Find sum using Stream.sorted().skip() method

  • First step is to sort an Array or List in natural order using Stream.sorted() method
  • Next step is to skip first (n-2) numbers in an Array or List using Stream.skip() method, so that only last 2 numbers will be remaining which is the largest
  • Finally sum/add the largest 2 numbers using Stream.reduce() method which returns result in integer form

FindingSumOfLargestTwoNumbersUsingStreamSkipMethod.java

package in.bench.resources.finding.sum;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

public class FindingSumOfLargestTwoNumbersUsingStreamSkipMethod {

	public static void main(String[] args) {

		// random numbers
		List<Integer> numbers = Arrays.asList(5, 9, 11, 2, 8, 21, 1);


		// Execution - start time
		LocalDateTime startDateTime = LocalDateTime.now();


		// find sum of largest 2 numbers using Stream.skip(); method
		int sum = numbers
				.stream()
				.sorted()
				.skip(numbers.size() - 2)
				.reduce(0,  Integer::sum);


		// Execution - end time
		LocalDateTime endDateTime = LocalDateTime.now();


		// find difference
		Duration duration = Duration.between(startDateTime, endDateTime);
		long differenceInNano = Math.abs(duration.getNano());


		// print sum to console
		System.out.println("The sum of 2 largest numbers in an Array is - "
				+ sum);


		// print execution time in Nano seconds
		System.out.println("\nExecution time using Stream.skip() method - "
				+ differenceInNano + " ns");
	}
}

Output:

The sum of 2 largest numbers in an Array is - 32

Execution time using Stream.skip() method - 24000000 ns

1.2 Find sum using Stream.sorted(Comparator).limit() method

  • First step is to sort an Array or List in reverse natural order using Stream.sorted(Comparator) method passing Comparator.reverseOrder() as argument – this will ensure first 2 numbers are largest in an Array
  • Next step is to limit first 2 numbers in an Array or List using Stream.limit() method – these 2 numbers are largest as we sorted in reverse natural order
  • Finally sum/add the largest 2 numbers using Stream.reduce() method which returns result in integer form

FindingSumOfLargestTwoNumbersUsingStreamLimitMethod.java

package in.bench.resources.finding.sum;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class FindingSumOfLargestTwoNumbersUsingStreamLimitMethod {

	public static void main(String[] args) {

		// random numbers
		List<Integer> numbers = Arrays.asList(5, 9, 11, 2, 8, 21, 1);


		// Execution - start time
		LocalDateTime startDateTime = LocalDateTime.now();


		// find sum of largest 2 numbers using Stream.limit(); method
		int sum = numbers
				.stream()
				.sorted(Comparator.reverseOrder())
				.limit(2)
				.reduce(0,  Integer::sum);


		// Execution - end time
		LocalDateTime endDateTime = LocalDateTime.now();


		// find difference
		Duration duration = Duration.between(startDateTime, endDateTime);
		long differenceInNano = Math.abs(duration.getNano());


		// print sum to console
		System.out.println("The sum of 2 largest numbers in an Array is - "
				+ sum);


		// print execution time in Nano seconds
		System.out.println("\nExecution time using Stream.limit() method - "
				+ differenceInNano + " ns");
	}
}

Output:

The sum of 2 largest numbers in an Array is - 32

Execution time using Stream.limit() method - 22000000 ns

1.3 Before Java 8 release

  • First we need to create a custom comparator to sort integers in descending order, so that first 2 numbers in an Array or List is the largest
  • NumberComparator class implements java.util.Comparator and defines reverse order sorting logic of integers which puts largest numbers on the top

NumberComparator.java

package in.bench.resources.finding.sum;

import java.util.Comparator;

public class NumberComparator implements Comparator<Integer> {

	@Override
	public int compare(Integer int1, Integer int2) {
		return int2 - int1;
	}
}

FindingSumOfLargestTwoNumbersBeforeJava8.java

  • First step is to sort an Array or List using Collections.sort() method passing 2 arguments where
    • 1st argument is List or Array to be sorted
    • 2nd argument is the Comparator for the sorting logic like reverse-order sorting or natural-order sorting
  • Next step is to iterate through an Array or List by limiting first 2 numbers and simultaneously doing addition/summation
package in.bench.resources.finding.sum;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class FindingSumOfLargestTwoNumbersBeforeJava8 {

	public static void main(String[] args) {

		// random numbers
		List<Integer> numbers = Arrays.asList(5, 9, 11, 2, 8, 21, 1);


		// Execution - start time
		LocalDateTime startDateTime = LocalDateTime.now();


		// sorting integers in reverse order using Comparator
		Collections.sort(numbers, new NumberComparator());


		// variable sum
		int sum = 0;


		// summing first 2 largest numbers
		for(int index = 0; index < numbers.size() && index < 2; index++) {

			sum += numbers.get(index);
		}


		// Execution - end time
		LocalDateTime endDateTime = LocalDateTime.now();


		// find difference
		Duration duration = Duration.between(startDateTime, endDateTime);
		long differenceInNano = Math.abs(duration.getNano());


		// print sum to console
		System.out.println("Before Java 8 - Sum of 2 largest numbers in an Array is - "
				+ sum);


		// print execution time in Nano seconds
		System.out.println("\nExecution time before Java 8 - "
				+ differenceInNano + " ns");
	}
}

Output:

Before Java 8 - Sum of 2 largest numbers in an Array is - 32

Execution time before Java 8 - 0 ns

2. Points to remember w.r.t execution time:

  • Execution time differs in different platforms
  • With small set of numbers, we may not find large difference in execution time
  • But with large set of numbers, difference will be significant to consider

3. List to Array to Stream conversion:

Above examples uses List as the base for finding smallest 2 numbers and then summing up them to get the desired result, but if we have Stream or Array instead of List then we can convert them into List using below approaches,

Happy Coding !!
Happy Learning !!

Java 8 - Find sum of Smallest 2 numbers in an Array or List or Stream
Java 8 - How to store multiple values for single key in HashMap ?