Home > OS >  Codingbat challenge: zeroMax Stream API Solution
Codingbat challenge: zeroMax Stream API Solution

Time:06-12

Given the task Test results

CodePudding user response:

Stream over the indices of your array, check if the current element equals zero, if not map it to itself, if yes stream once again over the rest of your array starting from current position using Arrays.stream(array, from, to) filter odds, find an optional max, if optional present return that orElse return the current element

public int[] zeroMax(int[] nums){
    boolean containsZero = java.util.stream.IntStream.of(nums).anyMatch(x -> x == 0);
    if (!containsZero) {
        return nums;
    }

    return java.util.stream.IntStream.range(0, nums.length).map(
            i -> nums[i] != 0 ? nums[i] : Arrays.stream(nums, i, nums.length)
                                                .filter(j -> j % 2 == 1)
                                                .max()
                                                .orElse(nums[i]))
            .toArray();
}
  • Related