【问题标题】:How to do operations within two same size collections如何在两个相同大小的集合中进行操作
【发布时间】:2019-04-02 15:11:18
【问题描述】:

假设有两个相同大小的 Integer ArrayList,是否有更有效的方法来获取由两个列表之间的差异组成的列表?
我的解决方法很简单但是好像不太好,随便贴一下:

// Assuming two same size list
List<Integer> listA = Arrays.asList(91,81,76,66,52);
List<Integer> listB = Arrays.asList(11,24,36,40,53);
List<Integer> diffList = new ArrayList<Integer>();
// I expect to get [80, 57, 40, 26, -1] back
for(int i = 0 ; i < listA.size(); i++){
    diffList.add(listA.get(i)-listB.get(i));
}

但我认为这不是一个好的解决方案。任何人都有更好的想法通过 Java 8 Stream 或其他一些数据结构来解决这个问题?

【问题讨论】:

  • 这是最简单的方法

标签: java data-structures iterator java-stream


【解决方案1】:

感谢@nullpointer 的帮助,我知道这两个列表大小是否不相等。

    boolean isALonger;
    if (listA.size() > listB.size()) {
        isALonger = true;
    } else {
        isALonger = false;
    }
    List<Integer> integers = IntStream.range(0, isALonger?listA.size():listB.size()).mapToObj(i -> {
        if (isALonger) {
            if (i < listB.size()) {
                return listA.get(i) - listB.get(i);
            } else {
                return listA.get(i);
            }
        } else {
            if (i < listA.size()) {
                return listA.get(i) - listB.get(i);
            } else {
                return - listB.get(i);
            }
        }
    }).collect(Collectors.toList());  

感谢 Holger 的建议。我修复了以下代码:

    int minSize = Math.min(listA.size(), listB.size());
    int maxSize = Math.max(listA.size(), listB.size());
    Stream<Integer> diffPart = IntStream.range(0, minSize).mapToObj(i -> listA.get(i) - listB.get(i));
    Stream<Integer> restPart = IntStream.range(minSize, maxSize).mapToObj(i -> listA.size() > listB.size() ? listA.get(i) :
            -listB.get(i));
    List<Integer> collect = Stream.concat(diffPart, restPart).collect(Collectors.toList());

【讨论】:

  • 不要使用 if(condition) variable = true; else variable = false; 这样的结构。你可以简单地写boolean isALonger = listA.size() &gt; listB.size();。此外,您可以简单地使用Math.max(listA.size(), listB.size())。并考虑不要重复测试你事先知道结果的条件。换句话说,您可以使用流到Math.min(listA.size(), listB.size()) 并映射到listA.get(i) - listB.get(i) 并从最小值流到Math.max(listA.size(), listB.size()) 并像i -&gt; isALonger? listA.get(i): -listB.get(i)) 一样映射并使用Stream.concat
  • 您可以内联diffPartrestPart,但是是的,这就是我的意思。
【解决方案2】:

由于问题标记为,因此您可以使用以下建议:

List<Integer> diffList = IntStream.range(0, listA.size())
        .mapToObj(i -> listA.get(i) - listB.get(i))
        .collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 2018-10-09
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多