从数组中删除元素

时间:2015-11-27 06:54:16

标签: java

如何从双精度数组中删除元素的所有出现。考虑

double[] arr = { 0.0,4.8,5.1,0.0,9.8}

我希望输出为{4.8,5.1,9.8}

4 个答案:

答案 0 :(得分:1)

借助java 8流的强大功能,您可以轻松完成!

double[] arr = {0.0, 4.8, 5.1, 0.0, 9.8};

double[] result = Arrays.stream(arr)
        .filter(e -> e != 0.0)
        .toArray();

System.out.println(Arrays.toString(result));

答案 1 :(得分:1)

你遍历数组元素,如果它不等于零,你会记住它,并增加计数器。在循环之后你会得到像

这样的东西

{4.8,5.1,9.8,0.0,9.8} current = 3。

然后你使用arr = Arrays.copyOf(arr,current);删除未使用的值 并获得新数组{4.8,5.1,9.8}

的结果
    double[] arr = {0.0, 4.8, 5.1, 0.0, 9.8};
    int current = 0;
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] != 0) {
            arr[current++] = arr[i];
        }
    }
    arr = Arrays.copyOf(arr, current);

答案 2 :(得分:0)

您必须创建一个新数组

List<Double> removals = Arrays.asList(arr);
while(removals.remove(0.00)) {}
double [] newArr = removals.toArray(new String[removals.size()]);
arr = newArr;

答案 3 :(得分:0)

Double[] numbers = {0.0,4.8,5.1,0.0,9.8};
    List<Double> list = new ArrayList<Double>(Arrays.asList(numbers));
    list.removeAll(Arrays.asList(Double.valueOf(0)));
    numbers = list.toArray(new Double[list.size()]);
    System.out.println(Arrays.toString(numbers));
}