Published On

Java Interview Prep: Part Two

Mastering Arrays in Java: Sorting, Summing, and Finding Key Values

Arrays are a fundamental data structure in Java, providing a way to store and manipulate collections of data. In this blog post, we'll explore various operations on arrays, such as sorting, summing, and finding specific values like the lowest and highest elements, median, and mode. We'll tackle a problem that involves performing these operations on an array of integers.

Problem Statement

Given an array of integers, we need to perform the following operations:

  1. Sort the array in ascending order.
  2. Sum all the values in the array.
  3. Sum a portion of the values in the array.
  4. Find the lowest 5 values.
  5. Find the highest 5 values.
  6. Find the median value.
  7. Find the most occurred value.
  8. Find the least occurred value (display list if multiple unique values).

For this problem, we can consider the following array:

App.java
public class App {
    public static void main(String[] args) {
        int[] numbers = {12, 4, 5, 3, 8, 7, 9, 10, 1, 6, 11, 2, 8, 7, 5};
    }
}

Step 1: Sort the Array

We can use Java's built-in Arrays.sort() method to sort the array in ascending order.

App.java
import java.util.Arrays;

public class App {
    public static void main(String[] args) {
        int[] numbers = {12, 4, 5, 3, 8, 7, 9, 10, 1, 6, 11, 2, 8, 7, 5};
        Arrays.sort(numbers);
        System.out.println("Sorted array: " + Arrays.toString(numbers));
    }
}

Step 2: Sum all the values

To sum all the values in the array, we can use a simple loop. For an even better solution we can use Arrays.stream() instead.

App.java
import java.util.Arrays;

public class App {
    public static void main(String[] args) {
        int[] numbers = {12, 4, 5, 3, 8, 7, 9, 10, 1, 6, 11, 2, 8, 7, 5};
        // Solution 1:
        int totalSum = 0;
        for (int num : numbers) {
            totalSum += num;
        }
        System.out.println("Total sum: " + totalSum);

        // Solution 2:
        int totalSum2 = Arrays.stream(numbers).sum();
        System.out.println("Total sum: " + totalSum2);
    }
}

Step 3: Summing a subsection of the array

To sum a portion of the values, say the first 5 values, we can use a loop. Similiar to the last problem, we can also use Arrays.stream()

App.java
import java.util.Arrays;

public class App {
    public static void main(String[] args) {
        int[] numbers = {12, 4, 5, 3, 8, 7, 9, 10, 1, 6, 11, 2, 8, 7, 5};
        // Solution 1:
        int portionSum = 0;
        for (int i = 0; i < 5; i++) {
            portionSum += numbers[i];
        }
        System.out.println("Sum of the first 5 values: " + portionSum);

        // Solution 2:
        int portionSum2 = Arrays.stream(numbers).limit(5).sum();
        System.out.println("Sum of the first 5 values: " + portionSum2);

    }
}
Comments