Using an IntStream
, you can easily sort it and skip the first element:
public int findSecondMin(int[] arr)
{
return IntStream.of(arr).sorted().skip(1).findFirst().orElse(Integer.MAX_VALUE);
}
But of course, you don't have to use streams. java.util.Arrays
has a nice sort method, and then you can just take the second element:
public int findSecondMin(int[] arr)
{
Arrays.sort(arr);
return arr.length < 2 ? Integer.MAX_VALUE : arr[1];
}
To avoid sorting the whole array, we can take your approach and adapt it into a custom reduction on the stream:
public int findSecondMin(int[] arr)
{
return IntStream.of(arr).boxed().reduce(
new int[] {Integer.MAX_VALUE, Integer.MAX_VALUE},
(mins, i) -> {
return new int[] {Math.min(i, mins[0]), Math.min(Math.max(i, mins[0]), mins[1])};
}, (mins1, mins2) -> {
int[] lesser = mins1[0] < mins2[0] ? mins1 : mins2;
int[] larger = mins1[0] < mins2[0] ? mins2 : mins1;
return new int[] {lesser[0], Math.min(lesser[1], larger[0])};
}
)[1];
}
Compared to a for loop based implementation, it might be harder to read, but can work in parallel.