简体   繁体   English

如何在两个相同大小的集合中进行操作

[英]How to do operations within two same size collections

Assuming there are two same size Integer ArrayLists, is there a more efficient way to get a list back which is composed of the difference between the two lists? 假设有两个相同大小的Integer ArrayLists,是否有更有效的方法来获取由两个列表之间的差异组成的列表?
My solution is very simple but seems not good, just post it anyway: 我的解决方案非常简单,但似乎并不好,无论如何都可以发布它:

// 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));
}

But I thought it was not a good solution. 但是我认为这不是一个好的解决方案。 Anyone has better idea to solve this question by Java 8 Stream or some data structure else? 有谁有更好的主意通过Java 8 Stream或其他某种数据结构来解决此问题?

Since the question is tagged with , hence a suggestion that you can use: 由于问题是用标记的,因此建议您使用:

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

Thanks for @nullpointer 's help, I got idea for if the two list size is not equivalent. 感谢@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());  

Thanks for Holger 's advices. 感谢Holger的建议。 I fixed code below: 我固定下面的代码:

    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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM