简体   繁体   English

将 int 数组转换为 ArrayList

[英]Conversion of int array to ArrayList

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.我有一个获取原始数据数组( int )的函数,我需要返回最小和最大两个元素的数组。 If length of the array is 1 then just return two first elements int the array.如果数组的长度为 1, int返回数组中的两个第一个元素。 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 ?但是如何将array转换为ArrayList Is there a more efficient way maybe?有没有更有效的方法?

By calling Collections.min and Collections.max , you're iterating over the array twice.通过调用Collections.minCollections.max ,您将遍历数组两次。 You can cut this time down by streaming the array and letting it do the heavy lifting, as James Mudd suggested .正如James Mudd 建议的那样,您可以通过流式传输阵列并让它完成繁重的工作来缩短此时间。 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};
}

You could use IntSummaryStatistics the method would look like您可以使用IntSummaryStatistics该方法看起来像

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

Here's another way of solving this task with streams.这是使用流解决此任务的另一种方法。

Instead, using IntSummuryStatistics we can provide an array of two elements as a container of the resulting values while applying collect and manually define to accumulate stream elements in it.相反,使用IntSummuryStatistics我们可以提供一个包含两个元素的数组作为结果值的容器,同时应用collect和手动定义来累积其中的流元素。

public static int[] minMax(int[] sourceArr) {
    
    if (sourceArr.length == 0) throw new IllegalArgumentException(); // source array is empty
    
    return Arrays.stream(sourceArr)
        .collect(
            () -> new int[]{sourceArr[0], sourceArr[0]}, // mutable container
            (arr, next) -> {                             // accumulator - populating the container with elements of the stream
                arr[0] = Math.min(arr[0], next);
                arr[1] = Math.max(arr[1], next);
            },
            (left, right) -> {                           // combiner - merging containers in parallel
                left[0] = Math.min(left[0], right[0]);
                left[1] = Math.max(left[1], right[1]);
            });
}

main()

public static int[] minMax(int[] sourceArr) {
    System.out.println(Arrays.toString(minMax(new int[]{3, 5, -3, 8, 9})));
    System.out.println(Arrays.toString(minMax(new int[]{3, -1, 3, 12, 27})));
}

Output:输出:

[-3, 9]
[-1, 27]

But how do I convert an array to an ArrayList ?但是如何将数组转换为ArrayList

It's not possible to convert an array of primitives into a List directly.无法基元数组直接转换为List When you have an array of reference type (like Integer , BigDecimal , etc.) you can use Arrays.asList() to fixed-size list wrapped around the given array.当您有一个引用类型的数组(如IntegerBigDecimal等)时,您可以使用Arrays.asList()将固定大小的列表包裹在给定的数组周围。 But it wouldn't work with primitive arrays.但它不适用于原始数组。

In order to translate int[] into a List<Integer> you have to create a new list and populate it with the contents of the array.为了将int[]转换为List<Integer>您必须创建一个新列表并用数组的内容填充它。

So your actual goal is to obtain the result as a list , the code provided above might be changed like that:因此,您的实际目标是获取结果为list ,上面提供的代码可能会更改为:

public static List<Integer> minMax(int[] sourceArr) {
    
    if (sourceArr.length == 0) throw new IllegalArgumentException(); // source array is empty
    
    return Arrays.stream(sourceArr)
        .collect(
            () -> Arrays.asList(sourceArr[0], sourceArr[0]), // mutable container
            (list, next) -> {                             // accumulator - populating the container with elements of the stream
                list.set(0, Math.min(list.get(0), next));
                list.set(1, Math.max(list.get(1), next));
            },
            (left, right) -> {                           // combiner - merging containers in parallel
                left.set(0, Math.min(left.get(0), right.get(0)));
                left.set(1, Math.max(left.get(1), right.get(1)));
            });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM