java - 从数组中删除特定元素

标签 java arrays

完成一个公共(public)静态方法的实现

greaterThan()

返回类型:int[]

参数列表:1个int[]array参数列表,1个int参数v

操作:返回一个新数组,其元素值为int[]数组参数列表中大于int参数v的值。 考虑以下代码段

int[] array = { 7, -1, -4, 2, 1, 6, 1, -3, 2, 0, 2, -7, 2, 8 };

int[] g1 = Determine.greaterThan( array, 2 );

int[] g2 = Determine.greaterThan( array, 7 );

int[] g3 = Determine.greaterThan( array, 9 );

导致数组变量

g1 表示一个 3 元素数组,元素值为 768

g2,并表示元素值为 8

的 1 元素数组

g3 表示 0 元素数组

这是我到目前为止所拥有的:

public class Determine {

// method greaterThan(): reutrns new int[] array whose element values are the ones
// in list greater than v 
public static int[] greaterThan( int[] list, int v){

    int n = list.length;
    int[] x = new int[ n ];

    for( int i = 0; i < n; i++ ){

        int value = list[i];
        if( value > v ){

            x[i] = value;
        }

    }

    return x;
  }  

}

但它给了我以下结果:

greaterThan( [ 7 -1 -4 2 1 6 1 -3 2 0 2 -7 2 8 ], 2 ): [ 7 0 0 0 0 6 0 0 0 0 0 0 0 8 ]

greaterThan( [ 7 -1 -4 2 1 6 1 -3 2 0 2 -7 2 8 ], 7 ): [ 0 0 0 0 0 0 0 0 0 0 0 0 0 8 ]

greaterThan( [ 7 -1 -4 2 1 6 1 -3 2 0 2 -7 2 8 ], 9 ): [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]

所以我基本上需要删除 0 来制作仅包含其余部分的数组!

最佳答案

在 Java 8 中,可以使用 filter() 轻松完成此操作:

static int[] greaterThan(int[] list, int v) {
    return Arrays.stream(list).filter(e -> e > v).toArray();
}

这是通过将 list 转换为流,然后过滤大于 v 的元素,再次将流转换为数组并返回它来实现的。

如果您无法使用 Java 8,或者不允许使用流,您可以使用 Arrays.copyOf() 来实现此目的:

static int[] greaterThan(int[] list, int v) {
    // Create an array with the same length as list
    int[] greaterThanV = new int[list.length];

    // Index to be used in by the greaterThanV array
    int numGreater = 0;
    for (int i = 0; i < list.length; i++) {
        int value = list[i];
        if (value > v) {
            // Store the value and increment the numGreater index
            greaterThanV[numGreater++] = value;
        }
    }
    // Return an array containing the first numGreater elements of greaterThanV
    return Arrays.copyOf(greaterThanV, numGreater);
}

与您的方法的区别在于,它使用 numGreater 作为结果数组 (greaterThanV) 的索引,并且仅在存储元素时才递增它。这意味着,如果您的调用相当于 greaterThan([7 -1 -4 2 1 6 1 -3 2 0 2 -7 2 8], 2),而不是返回:

[7 0 0 0 0 6 0 0 0 0 0 0 0 8]

greaterThanV 数组将包含:

[7 6 8 0 0 0 0 0 0 0 0 0 0 0]

最后,由于我们存储了三个值,numGreater 将是 3。因此,当我们这样做时:

Arrays.copyOf([7 6 8 0 0 0 0 0 0 0 0 0 0 0], 3)

我们得到修剪后的数组作为结果:

[7 6 8]

关于java - 从数组中删除特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29264182/

相关文章:

java - IndexOfMaxInRange 的问题

java - 逻辑或和短路或运算符有什么区别?

java - 如何限制 ItemtouchHelper 只能从左向右滑动

ruby-on-rails - Ruby 从数组中计算总和

javascript - Node : How to replace certain characters within an array with other characters in javascript

c# - .MakeArrayType() 和 .MakeArrayType(1) 的区别

java - Spring - 将 BindingResult 添加到新创建的模型属性

java - 如何将 Google 的 PlaceAutoCompleteFragment 实现到扩展 Fragment 的类中

ios - SwiftyJSON 转换为多个字符串数组

java - 获取泛型类型的数组类