Java 8 Features (Part 1)
To start with, we will go over a simple yet interesting problem in Java: finding the second smallest value in an array. There are a few different approaches we could take. The most obvious would be sorting the array, skipping the first element (and any duplicates). However, a more efficient approach could be taken as follows:
First, instantiate a simple int array and find the minimum as you usually would.
int[] arr = {5, 44, 0, 0, 99};
NoSuchElementException exception = new NoSuchElementException("Array is empty");
int min1 = Arrays.stream(arr)
.min()
.orElseThrow(() -> exception);
Then, simply filter out that first minimum value from the array and find the minimum of that subarray respectively.
int min2 = Arrays.stream(arr)
.filter(x -> x != min1)
.min()
.orElseThrow(() -> exception);
System.out.print(min2);
This approach saves on time complexity and feels more readable in my personal opinion. I thought it would be interesting to share this cool snippet with everyone!
Coming Soon in Part 2: Information about CompletableFuture in Java 8!
© Kevin Siraki.RSS