代码之家  ›  专栏  ›  技术社区  ›  Saikat SHASHANK HONRAO

使用Java流比较两个整数数组

  •  7
  • Saikat SHASHANK HONRAO  · 技术社区  · 6 年前

    我有两个整数数组-

    int[] a = {2, 7, 9}

    int[] b = {4, 2, 8}

    2 4 然后 7 最后呢 9 8 . 每个比较结果都将存储在一个列表中。

    4 回复  |  直到 5 年前
        1
  •  7
  •   Ravindra Ranwala    6 年前

    你可以这样做,

    List<Boolean> equalityResult = IntStream.range(0, a.length).mapToObj(i -> a[i] == b[i])
                    .collect(Collectors.toList());
    

    前提条件:两个数组大小相同。

        2
  •  3
  •   Naman    6 年前

    假设两个输入数组的长度相同

    List<Integer> list = IntStream.range(0, a.length).mapToObj(i -> Integer.compare(a[i], b[i]))
                .collect(Collectors.toCollection(() -> new ArrayList<>(a.length)));
    
        3
  •  2
  •   Hadi Jeddizahed    6 年前

    List<Integer> result = IntStream.rangeClosed(0,a.length-1)
                .boxed()
                .map(i->Integer.compare(a[i],b[i]))
                .collect(Collectors.toList());
    
        4
  •  2
  •   Ousmane D.    6 年前

    您实际上是在寻找 Zip 操作(在Java中还不可用)。

    boolean[] accumulator = new boolean[a.length];
    IntStream.range(0, a.length)
             .forEachOrdered(i -> accumulator[i] = a[i] == b[i]);
    

    分别得到一个 int 在两个数组中的相应元素之间:

    int[] ints = IntStream.range(0, a.length)
                          .map(i -> Integer.compare(a[i], b[i]))
                          .toArray();