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

如何对两个Integer列表执行逐位相减以获取差值列表

如何实现两个列表的逐位相减?

嘿,这事儿不难,咱们直接针对你给出的需求来实现就行。先明确核心要求:对两个长度相同的Integer列表,取对应索引位置的元素做减法(你写的j应该是笔误,实际是bookingList.get(i) - bookedList.get(i)),最终得到目标结果列表。

前提注意

注意:在执行操作前,请确保bookingList和bookedList的长度完全相同,否则会抛出IndexOutOfBoundsException异常。如果存在长度不一致的可能,可以提前做兼容处理。


方法1:传统for循环(逻辑清晰,适合初学者)

这种方式最直观,通过遍历索引逐个计算差值:

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

public class ListSubtractionExample {
    public static void main(String[] args) {
        // 你的输入列表
        List<Integer> bookingList = List.of(3, 4, 5, 6, 5, 5);
        List<Integer> bookedList = List.of(1, 2, 3, 2, 3, 4);
        List<Integer> finalList = new ArrayList<>();

        // 逐位计算差值并添加到结果列表
        for (int i = 0; i < bookingList.size(); i++) {
            int difference = bookingList.get(i) - bookedList.get(i);
            finalList.add(difference);
        }

        // 验证结果
        System.out.println(finalList); // 输出:[2, 2, 2, 4, 2, 1]
    }
}

方法2:Java 8+ Stream API(简洁优雅)

如果你熟悉Java 8及以上的流式编程特性,可以用更简洁的写法:

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

public class ListSubtractionStreamExample {
    public static void main(String[] args) {
        List<Integer> bookingList = List.of(3, 4, 5, 6, 5, 5);
        List<Integer> bookedList = List.of(1, 2, 3, 2, 3, 4);

        // 用IntStream生成索引,映射计算差值后收集为列表
        List<Integer> finalList = IntStream.range(0, bookingList.size())
                .map(i -> bookingList.get(i) - bookedList.get(i))
                .boxed()
                .collect(Collectors.toList());

        System.out.println(finalList); // 输出:[2, 2, 2, 4, 2, 1]
    }
}

处理列表长度不一致的情况

如果无法保证两个列表长度相同,可以先取它们的最小长度来循环,避免索引越界:

int minSize = Math.min(bookingList.size(), bookedList.size());
for (int i = 0; i < minSize; i++) {
    int difference = bookingList.get(i) - bookedList.get(i);
    finalList.add(difference);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:38:34