代码之家  ›  专栏  ›  技术社区  ›  Mani

BinaryOperator for list<integer>添加列表

  •  2
  • Mani  · 技术社区  · 7 年前

    在上一个问题中,我之前问过 Which FunctionalInterface should I use?

    现在我想补充一下 List<Integer> 不止两个 整数 a b ,以便每个索引都添加到另一个列表的同一索引中。

    我以前

     BinaryOperator<Integer> binaryOperator = Integer::sum;
    

    用于添加两个整数,使用 binaryOperator.apply(int a,int b) . 有类似的方法吗

    BinaryOperator<List<Integer>> binaryOperator = List<Integer>::sum;
    

    然后得到结果 List<Integer> cList 是吗?

    3 回复  |  直到 7 年前
        1
  •  4
  •   Ousmane D.    7 年前

    如果要在相应的索引处对元素执行一些计算(在这种特定情况下是求和),则不需要使用 BinaryOperator ,而是使用 IntStream.range 要生成索引:

    // generates numbers from 0 until list.size exclusive 
    IntStream.range(0, list.size())....
    
    // generates numbers from 0 until the minimum of the two lists exclusive if needed
    IntStream.range(0, Math.min(list.size(), list2.size()))....
    

    这种类型逻辑的通用名称是“zip”;即,当给定两个输入序列时,它会生成一个输出序列,其中来自相同位置输入序列的每两个元素都使用某种函数组合在一起。

    标准库中没有用于此的内置方法,但您可以找到一些通用实现 here .

    例如,使用 zip 方法在链接帖子的已接受答案中,您可以简单地执行以下操作:

    List<Integer> result = zip(f.stream(), s.stream(), (l, r) -> l + r).collect(toList());
    

    或使用方法参考:

    List<Integer> result = zip(f.stream(), s.stream(), Math::addExact).collect(toList());
    

    哪里 f s 是整数列表。

        2
  •  1
  •   Naman    7 年前

    你可以使用 IntStream.range() 迭代元素,然后 mapToObj() 将它们映射到它们的总和和 collect() 它们在第三个列表中。

    鉴于你的名单是 相同大小

    List<Integer> first = List.of(); // initialised
    List<Integer> second = List.of(); // initialised
    

    第三个列表可以是:

    List<Integer> third = IntStream.range(0, first.size())
                                   .mapToObj(i -> first.get(i) + second.get(i))
                                   .collect(Collectors.toList());
    

    对于BinaryOperator,可以将其表示为:

    BinaryOperator<List<Integer>> listBinaryOperator = (a, b) -> IntStream.range(0, first.size())
                .mapToObj(i -> first.get(i) + second.get(i))
    //          OR from your existing code
    //          .mapToObj(i -> binaryOperator.apply(first.get(i), second.get(i)))
                .collect(Collectors.toList());
    

    或者,您可以通过将逻辑抽象为一个方法并将其用作:

    BinaryOperator<List<Integer>> listBinaryOperator = YourClass::sumOfList;
    

    哪里 sumOfList 定义为:

    private List<Integer> sumOfList(List<Integer> first, List<Integer> second) {
        return IntStream.range(0, first.size())
                .mapToObj(i -> first.get(i) + second.get(i))
                .collect(Collectors.toList());
    }
    
        3
  •  1
  •   HPH    7 年前

    您可以做的是定义自己的实用方法,它的单个任务是 拉链 两个输入列表:

    <T> List<T> zip(final List<? extends T> first, final List<? extends T> second, final BinaryOperator<T> operation)
    {
        return IntStream.range(0, Math.min(first.size(), second.size()))
            .mapToObj(index -> operation.apply(first.get(index), second.get(index)))
            .collect(Collectors.toList());
    }
    

    这样,您可以将两个输入列表求和为:

    zip(first, second, Integer::sum)
    
    推荐文章