Java 8 – Find sum of Smallest 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 smallest 2 numbers in an Array or List or Stream

1. Finding sum of 2 Smallest numbers in an Array

  1. Using Stream.sorted().limit() method
  2. Using Stream.sorted(Comparator).skip() method

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

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

FindingSumOfSmallestTwoNumbersUsingStreamLimitMethod.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 FindingSumOfSmallestTwoNumbersUsingStreamLimitMethod {

	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() // natural ordering
				.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 smallest 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 smallest numbers in an Array is - 3

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

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

  • First step is to sort an Array or List in reverse natural order using Stream.sorted(Comparator) method passing Comparator.reverseOrder() as argument
  • 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 smallest
  • Finally sum/add the smallest 2 numbers using Stream.reduce() method which returns result in integer form

FindingSumOfSmallestTwoNumbersUsingStreamSkipMethod.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 FindingSumOfSmallestTwoNumbersUsingStreamSkipMethod {

	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(Comparator.reverseOrder()) // reverse natural ordering
				.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 smallest 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 smallest numbers in an Array is - 3

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

1.3 Before Java 8 release

  • First step is to sort an Array or List using Collections.sort() method passing actual Array or List to be sorted which sorts in the natural order i.e., smallest numbers on the top
  • Next step is to iterate through an Array or List by limiting first 2 numbers and simultaneously doing addition/summation

FindingSumOfSmallestTwoNumbersBeforeJava8.java

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 FindingSumOfSmallestTwoNumbersBeforeJava8 {

	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 natural order
		Collections.sort(numbers);


		// 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 smallest 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 smallest numbers in an Array is - 3

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 - How to Merge or Concatenate 2 Arrays using Stream API
Java 8 - Find sum of Largest 2 numbers in an Array or List or Stream