Home > other >  Conversion of int array to ArrayList
Conversion of int array to ArrayList

Time:07-18

I have a function that gets an array of primitive data (int), I need to return the array of two elements the smallest and the largest number. If length of the array is 1 then just return two first elements int the array. I came up with such solution:

public static int[] minMax(int[] arr) {
    if (arr.length==1)
        return new int[]{arr[0],arr[0]} ;// return if arr is 1 element
    else {
        ArrayList<Integer> ar = new ArrayList<Integer>();
        //?
        return new int[]{Collections.max(ar),Collections.min(ar)};
    }
}

But how do I convert an array to an ArrayList? Is there a more efficient way maybe?

CodePudding user response:

By calling Collections.min and Collections.max, you're iterating over the array twice. You can cut this time down by streaming the array and letting it do the heavy lifting, as James Mudd suggested. However, note that by doing so you'd be wasting time on calculating the sum and accumulating the count of the elements, which you don't care about. It may be more efficient to calculated these yourself:

public static int[] minMax(int[] arr) {
    // Assuming arr has at least one element
    int min = arr[0];
    int max = arr[0];
    for (int i = 1; i < arr.length;   i) {
        int curr = arr[i];
        if (curr < min) {
            min = curr;
        } else if (curr > max) {
            max = curr;
        }
    }
    return new int[]{min, max};
}

CodePudding user response:

You could use IntSummaryStatistics the method would look like

public static int[] minMax(int[] arr) {
    IntSummaryStatistics intSummaryStatistics = Arrays.stream(arr).summaryStatistics();
    return new int[] {intSummaryStatistics.getMin(), intSummaryStatistics.getMax()};
}
  • Related