列表中的Java频率

  • 本文关键字:频率 Java 列表 java
  • 更新时间 :
  • 英文 :


问题出在nullpointexception上。当我输入例如:1 1 1 4时,一切都很好,因为输入的大小与数组的大小相同。但如果我输入1 1 4-我会出现异常,无法解决。也许有人对此有任何想法?

您必须使用Map来保留number->frequency数据。您可以使用流按数据分组

Map<Integer, Long> counted = list.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

我认为这是某种赋值,所以您应该在不使用高级预构建的java算法的情况下解决这个问题。当你试图自己解决问题时,我愿意帮忙。您的主要问题与算法本身无关,而是与一些关于装箱/开箱的Java特性有关:您试图访问的数组元素是null,在这种情况下,转换为整数(开箱(将不起作用,并抛出一个NullPointerException

与其解决NullPointerException问题,我建议从头开始复习作业:

如果我们假设,我们已经知道输入数字的最小值和最大值,那么很容易计算所有输入数字的频率:

/**
* @param input the input numbers
* @param min   the minimum input number (min(input))
* @param max   the maximum input number (max(input))
* @return      the frequency of all input numbers as array. The n-th array element denotes the frequence of the number n+min.
*/
int[] frequency(int[] input, int min, int max) {
int[] result = new int[max - min + 1];  // e.g. int[4] for min = 2 and max = 5
for(int i = 0; i < input.length; ++i) { // iterate all input numbers
int n = input[i];    // the number
int index = n - min; // the index in the frequency array
result[index]++;
}
return result;
}

最小值和最大值可以很容易地计算如下:

/**
* Computes the boundaries (minimum and maximum) of the given number array
* @param input the input numbers
* @return      the minimum and maximum number of the input numbers as array of length 2. The first element is the minimum, the second element the maximum value.
*/
int[] boundaries(int[] input) {
int[] result = new int[2]; // result[0] = min, result[1] = max
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for(int i = 0; i < input.length; ++i) {
int n = input[i];
min = Math.min(min, n);
max = Math.max(max, n);
}
return new int[] { min, max };
}

剩下的很简单:

/**
* Computes the frequencies of the given input numbers.
* @returns the frequencies of the input numbers as two-dimensional array. The first element of the array is an array of the frequencies, the second element the array of numbers. 
*/
int[][] frequencies(int[] input) {
// get min/max of input
int[] minMax = boundaries(input);
int min = minMax[0];
int max = minMax[1];
// compute frequencies
int[] frequencies = frequency(input, min, max);
// create numbers array
int[] numbers = new int[frequencies.length]);
for(int i = 0; < frequency.length; ++i) {
numbers[i] = min + i;
}
// assembly two dimensional result array
return new int[][] { frequencies, numbers };
}

所有这些都可以通过使用java运行时环境的内置机制(例如用于计算最小/最大值的streaming-API(来更简单地完成。

Integer maxSize=Collections.max(arrList(;

返回集合中的最大元素。

使用Integer maxSize = arrList.size()

而不是Integer maxSize = Collections.max(arrList);

从技术上讲,您可以使用Collection并在其上执行Collection。frequency(Collection,Object(,而不是数组。

返回指定集合中等于指定的对象。更正式地说,返回元素的数量e在集合中,这样Objects.equals(o,e(。

收藏。频率​(集合c,对象o(

最新更新