Common Arrays API Methods
The java.util.Arrays clas provides several static utility methods to manipulate arrays efficiently. Below is a demonstration of primary array operations:
import java.util.Arrays;
import java.util.Comparator;
public class ArrayOperations {
public static void main(String[] args) {
int[] data = {5, 2, 9, 1, 7, 6};
// Convert array to string representation
System.out.println("String view: " + Arrays.toString(data));
// Binary Search (Array must be sorted first)
Arrays.sort(data);
int index = Arrays.binarySearch(data, 7);
System.out.println("Index of 7: " + index);
// Copy operations
int[] copy = Arrays.copyOf(data, data.length);
int[] subset = Arrays.copyOfRange(data, 1, 3);
System.out.println("Subset: " + Arrays.toString(subset));
// Fill array with a constant value
int[] filled = new int[5];
Arrays.fill(filled, 100);
System.out.println("Filled array: " + Arrays.toString(filled));
}
}
Introduction to Lambda Expressions
Lambda expressions allow for a more concise syntax when implmeenting functional interfaces—interfaces that contain exactly one abstract method. They replace the verbose syntax of anonmyous inner classes.
Custom Sorting with Comparators
Before Java 8, custom sorting required an anonymous inner class:
Integer[] values = {10, 5, 8, 2};
Arrays.sort(values, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a - b;
}
});
Simplifying with Lambdas
Using a Lambda expression, the same logic is reduced significantly:
Integer[] values = {10, 5, 8, 2};
Arrays.sort(values, (a, b) -> a - b);
Lambda Syntax Shortcuts
- Type Inference: Parameter types (e.g.,
Integer) can be omitted as the compiler infers them. - Single Parameter: If there is only one parameter, parentheses around it are optional.
- Concise Body: If the body consists of a single statement, the braces, semicolon, and
returnkeyword can be omitted.
Practical Application: Sorting by String Length
The following example demonstrates sorting an array of strings based on their length rather than alphabetical order, utilizing the concise lambda syntax:
public class StringLengthSort {
public static void main(String[] args) {
String[] words = {"apple", "kiwi", "banana", "fig"};
// Sort by length: shortest to longest
Arrays.sort(words, (s1, s2) -> s1.length() - s2.length());
for (String word : words) {
System.out.println(word);
}
}
}