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:
- Sort the array in ascending order.
- Sum all the values in the array.
- Sum a portion of the values in the array.
- Find the lowest 5 values.
- Find the highest 5 values.
- Find the median value.
- Find the most occurred value.
- Find the least occurred value (display list if multiple unique values).
For this problem, we can consider the following array:
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.
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.
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()
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);
}
}