在数组列表中计算有条件的元素



我应该根据某些条件返回myList元素计数。 要计数的每个Integer元素的条件为:

不少于40

public int count(ArrayList<Integer> aMyList) {
int count = 0;
for (int aInteger : aMyList) {
if (aInteger <= 40)
count++;
}
return count;
}

有什么问题吗?提前谢谢。

您的代码将返回小于 40 的元素数,但我从您的文本中假设您想要计算完全相反的元素数,即大于 40 的元素数。如果是这种情况,您的代码必须如下所示:

public int count(ArrayList<Integer> aMyList) {
int count = 0;
for (int aInteger : aMyList) {
if (aInteger >= 40) // Here is the difference
count++;
}
return count;
}
布尔

逻辑和逻辑等价

假设您的状况是:

少于40

这将从字面上表示为等同于aInteger >= 40的条件!(aInteger < 40)

问题和解决方案

所以你的方法几乎是正确的,除了条件:它计算指定列表中小于或等于 40的所有Integer元素,aInteger <= 40.

但是你说not less than 40相当于greater than or equal 40

public int count(ArrayList<Integer> aMyList) {
int count = 0;
for (int aInteger : aMyList) {
// if (aInteger <= 40) // Yours was equivalent to: less than or equal 40
if (aInteger >= 40) // equivalent to: NOT less than 40
count++;
}
return count;
}

使用 Java 8 流

您还可以使用流式处理功能:

// method-name: express what it does
// parameter: renamed simpler, also typed more generic as interface
public int countElementsGreaterOrEqual40(List<Integer> list) {
Predicate<Integer> greaterOrEqual40 = i-> i >= 40;  // predicate: true if not less than 40 
return (int) list.stream().filter(greaterOrEqual40).count(); // filter elements on predicate=true; then count the filtered elements
}

请参阅 Java 8 Stream 示例,Stream.count

您的代码不正确。查看下面的代码。如果您需要任何修改,请告诉我们。

public int count(ArrayList<Integer> aMyList) {
int count = aMyList.size();
if(count >= 40){
return count;
}
return count;
}

最新更新