我想知道如何从数组中删除某些元素

时间:2018-07-27 01:45:45

标签: java arrays

在此程序中,我希望能够从数组中删除最小值和最大值,但是我不知道该怎么做。

public class Average
{

  public static void main (String [ ] args) 
  {

    double [] weights = {39.5, 34.8, 22.6, 38.7, 25.4, 30.1, 41.8, 33.6, 26.2, 27.3};
    double minimum = Integer.MAX_VALUE;
    double maximum = Integer.MIN_VALUE;

    for(int i = 0; i < weights.length; i++){
        if(minimum > weights [i])
            minimum = weights[i];
    }

    for(int i = 0; i < weights.length; i++){
        if(maximum < weights [i])
            maximum = weights[i];
    }
  } 
}

3 个答案:

答案 0 :(得分:2)

使用Java 8,您可以使用stream到数组中的filter不需要的内容。为了在filter方法中使用最小和最大变量,必须将它们放在final变量中。您在filter方法中看到的w是一个局部变量,代表每个元素值。

您也不必遍历数组来查找最小值和最大值。只需使用if/else if来设置适当的最小值/最大值。

import java.util.Arrays;

public class StackOverflow {
    public static void main(String args[]) {
        double[] weights = { 39.5, 34.8, 22.6, 38.7, 25.4, 30.1, 22.6, 41.8, 33.6, 26.2, 27.3 };
        double minimum = Double.MAX_VALUE;
        double maximum = Double.MIN_VALUE;

        for (int i = 0; i < weights.length; i++) {
            if (minimum > weights[i])
                minimum = weights[i];
            else if (maximum < weights[i])
                maximum = weights[i];
        }

        System.out.println("Before: " + Arrays.toString(weights));

        final double minimumFilter = minimum;
        final double maximumFilter = maximum;
        weights = Arrays.stream(weights)
                .filter(w -> w != minimumFilter && w != maximumFilter)
                .toArray();

        System.out.println("After : " + Arrays.toString(weights));
    }
}

结果:

Before: [39.5, 34.8, 22.6, 38.7, 25.4, 30.1, 22.6, 41.8, 33.6, 26.2, 27.3]
After : [39.5, 34.8, 38.7, 25.4, 30.1, 33.6, 26.2, 27.3]
// Two 22.6 minimum was removed and one 41.8 maximum was removed.

答案 1 :(得分:0)

有多种方法可以解决此问题。

  1. 遍历数组并跳过所需的索引,并将所有剩余值存储到新数组中。
  2. 使用数组复制来复制没有最小值和最大值的元素。
  
      
  1. 但是我建议为此使用收集框架。
  2.   
List<Double> weights = new ArrayList<Double>();

最好使用ArrayList而不是普通数组,这样仅通过提供索引即可轻松删除任何节点。但是,即使您只想使用数组,也可以将Array转换为List,然后删除元素,然后再次将List转换为Array

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class Average {

    public static void main(String[] args) {

        double[] weights = { 39.5, 34.8, 22.6, 38.7, 25.4, 30.1, 41.8, 33.6, 26.2, 27.3 };
        double minimum = Integer.MAX_VALUE;
        double maximum = Integer.MIN_VALUE;
        int minIndex = -1;
        int maxIndex = -1;

        for (int i = 0; i < weights.length; i++) {
            if (minimum > weights[i]) {
                minimum = weights[i];
                minIndex = i;
            }
        }

        for (int i = 0; i < weights.length; i++) {
            if (maximum < weights[i]) {
                maximum = weights[i];
                maxIndex = i;
            }
        }

        List<Double> list = Arrays.stream(weights).boxed().collect(Collectors.toList());
        list.remove(minIndex);
        if(minIndex<maxIndex)
            list.remove(maxIndex-1);
        else
            list.remove(maxIndex);

        weights = list.stream().mapToDouble(Double::doubleValue).toArray();

        for (double weight : weights) {
            System.out.print(weight + " ");
        }
    }
}

答案 2 :(得分:0)

我认为您最好将如下所示的逻辑封装在工具方法中:

RespondToAuthChallenge

作为您的输入并进行以下本地测试:

// This join is performed in memory
var results =
    from e in Enum.GetValues(typeof(Roles)).Cast<Roles>()
    join r in ApplicationUser on e equals r.Roles into rs
    from r in rs.DefaultIfEmpty()
    select new { Roles = e, Count = r?.Count ?? 0};

结果将是:

// all minimums and maximums in the array will be deleted and return a brand-new array;
public static Double[] removeMinMax(Double[] arr) {
    if (arr == null || arr.length == 0) throw new IllegalArgumentException();
    // a trick to be used avoid lambda `effectively final` check;
    Double[] minMax = {arr[0], arr[0]};
    for (int i = 0; i < arr.length; ++i) {
        if (minMax[0].compareTo(arr[i]) > 0) minMax[0] = arr[i];
        if (minMax[1].compareTo(arr[i]) < 0) minMax[1] = arr[i];
    }
    return Arrays.stream(arr)
            .filter(a -> a.compareTo(minMax[0]) != 0 && a.compareTo(minMax[1]) != 0)
            .toArray(Double[]::new);
}