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

使用Java 8 Streams改写两数和为8的数组验证代码

使用Java 8特性改写两数之和判断逻辑

问题描述

给定一个整数列表,判断列表中是否存在两个数相加等于目标值(示例中为8)。以下是传统嵌套循环的实现代码,我们将用Java 8的Stream API等特性提供多种替代实现方式。

传统循环实现

import java.util.List;

public class Main {

    static List<Integer> arrayOne = List.of(1,3,6,9);
    static List<Integer> arrayTwo = List.of(1,6,2,10);

    static boolean validateArray(int result, List<Integer> array){
        for (int i = 0; i<array.size() - 1; i++){
            for (int j = i + 1; j < array.size(); j ++){
                int value1 = array.get(i);
                int value2 = array.get(j);
                if(value1 + value2 == result){
                    return true;
                }
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(validateArray(8, arrayTwo));
    }
}

Java 8 替代实现方案

方案1:Stream嵌套flatMap + anyMatch(模拟传统循环逻辑)

该方案用Stream API模拟传统嵌套循环的逻辑,遍历所有i<j的数对,通过anyMatch短路判断是否存在符合条件的组合。

import java.util.List;
import java.util.stream.IntStream;

public class Main {

    static List<Integer> arrayOne = List.of(1,3,6,9);
    static List<Integer> arrayTwo = List.of(1,6,2,10);

    static boolean validateArrayWithStream(int target, List<Integer> array) {
        return IntStream.range(0, array.size())
                // 对每个索引i,生成i之后的所有索引j,映射为对应的数对
                .flatMap(i -> IntStream.range(i + 1, array.size())
                        .mapToObj(j -> new int[]{array.get(i), array.get(j)}))
                // 检查是否存在数对和为target,找到即返回true
                .anyMatch(pair -> pair[0] + pair[1] == target);
    }

    public static void main(String[] args) {
        System.out.println(validateArrayWithStream(8, arrayTwo));
    }
}

特点:逻辑和传统循环完全对应,容易理解;时间复杂度仍为O(n²),适合小数据量场景。

方案2:Stream + HashSet(高效O(n)实现)

利用HashSet的O(1)查找特性,将时间复杂度优化到O(n),仅需遍历一次列表。

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {

    static List<Integer> arrayOne = List.of(1,3,6,9);
    static List<Integer> arrayTwo = List.of(1,6,2,10);

    static boolean validateArrayWithSet(int target, List<Integer> array) {
        Set<Integer> seenNumbers = new HashSet<>();
        return array.stream()
                .anyMatch(num -> {
                    // 检查是否已存在能与当前数相加得到target的元素
                    if (seenNumbers.contains(target - num)) {
                        return true;
                    }
                    // 将当前数存入集合,供后续元素检查
                    seenNumbers.add(num);
                    return false;
                });
    }

    public static void main(String[] args) {
        System.out.println(validateArrayWithSet(8, arrayTwo));
    }
}

特点:时间复杂度O(n),空间复杂度O(n),大数据量场景下性能远优于嵌套循环;利用anyMatch的短路特性,找到符合条件的组合后立即终止遍历。

方案3:使用Stream的reduce(思路拓展)

通过reduce操作维护一个HashSet,逐步检查并更新集合,最终判断是否存在符合条件的组合。该方式可读性不如前两种,仅作思路参考。

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {

    static List<Integer> arrayOne = List.of(1,3,6,9);
    static List<Integer> arrayTwo = List.of(1,6,2,10);

    static boolean validateArrayWithReduce(int target, List<Integer> array) {
        return array.stream()
                .reduce(new HashSet<>(), (set, num) -> {
                    if (set.contains(target - num)) {
                        // 标记找到符合条件的组合
                        set.add(-1);
                    } else if (!set.contains(-1)) {
                        set.add(num);
                    }
                    return set;
                }, (s1, s2) -> s1)
                .contains(-1);
    }

    public static void main(String[] args) {
        System.out.println(validateArrayWithReduce(8, arrayTwo));
    }
}

特点:利用reduce的累积特性传递状态,但需要借助特殊值标记结果,可读性较差,实际场景较少使用。

内容的提问来源于stack exchange,提问作者MATEO VALENCIA MINOTA

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:10:32