You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效实现无需双循环从原数组筛选阈值以上元素至新数组

优化方案

方案1:用Stream API一行搞定(Java 8+)

这是最简洁的实现方式,利用Java 8引入的Stream流处理,一次遍历完成过滤和数组转换:

import java.util.Arrays;

public int[] getValuesAboveThreshold(int threshold) {
    return Arrays.stream(data)
                 .filter(num -> num > threshold)
                 .toArray();
}

方案2:用ArrayList单遍历收集(兼容所有Java版本)

如果需要兼容Java 8之前的版本,用ArrayList先收集符合条件的元素,最后转成数组,全程只遍历一次原数组:

import java.util.ArrayList;
import java.util.List;

public int[] getValuesAboveThreshold(int threshold) {
    List<Integer> tempList = new ArrayList<>();
    for (int num : data) {
        if (num > threshold) {
            tempList.add(num);
        }
    }
    // 把ArrayList转成int数组
    int[] thresholdArray = new int[tempList.size()];
    for (int i = 0; i < tempList.size(); i++) {
        thresholdArray[i] = tempList.get(i);
    }
    return thresholdArray;
}

方案3:手动单循环处理(无集合依赖)

要是不想用集合框架,可以先创建一个和原数组等长的临时数组,收集完有效元素后再截取有效部分,同样只遍历一次:

import java.util.Arrays;

public int[] getValuesAboveThreshold(int threshold) {
    int[] tempArray = new int[data.length];
    int count = 0;
    for (int num : data) {
        if (num > threshold) {
            tempArray[count++] = num;
        }
    }
    // 截取仅包含有效元素的数组返回
    return Arrays.copyOf(tempArray, count);
}

为什么这些方案更好?

原来的双循环需要遍历两次原数组,当数组规模较大时,单遍历方案能直接减少一半的遍历操作,效率更高。而且代码逻辑更简洁,可读性更强,不用手动维护计数和两次循环的重复判断逻辑。

内容的提问来源于stack exchange,提问作者WhosWho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:40:22