【问题标题】:Count elements conditional in ArrayList [closed]计算ArrayList中的条件元素[关闭]
【发布时间】:2020-04-01 17:36:57
【问题描述】:

我应该在某些条件下返回myList 中的元素计数。 每个要计数的Integer 元素的条件是:

不少于40

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

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

【问题讨论】:

  • “有什么问题吗?”为什么不测试一下?
  • 将您的条件更改为aInteger &gt;= 40
  • @SunilDabburi 如何整数> 40?
  • 我更新了我的评论。看到这个问题。 not less than 40
  • 问题一点都不清楚。请改写问题

标签: java arraylist conditional-statements counting


【解决方案1】:

布尔逻辑和逻辑等价

假设你的条件是:

小于40

这将按字面意思表示为有条件的!(aInteger &lt; 40),相当于aInteger &gt;= 40

问题及解决办法

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

但是你说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 examples, Stream.count

【讨论】:

  • 由于 List 的 size() 的最大结果将是 int 我决定强制转换并更正我的代码。
【解决方案2】:

您的代码将返回小于 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;
}

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 您的代码返回列表的大小(即使它大于或等于 40)。 OP 要求根据条件计算元素。
    猜你喜欢
    • 2023-03-07
    • 2022-01-02
    • 2023-04-01
    • 2012-04-25
    • 2012-10-17
    • 2017-11-06
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    相关资源
    最近更新 更多