简体   繁体   English

如何比较数组元素并将相应的元素添加到第三个数组?

[英]How to compare array elements and add corresponding elements to a third array?

Below is my code where I want to compare two array elements and add corresponding elements to a new array( foundArray ) and not found elements to other array( notFoundArray ). 下面是我的代码,在这里我想比较两个数组元素并将相应的元素添加到新数组( foundArray )中,而未找到的元素添加到其他数组( notFoundArray )中。

public static void main(String[] args) {

    Integer[] originalArray = { 12, 54, 19, 20, 44, 32, 14, 63, 57, 28 };
    Integer[] keyArray = { 20, 44, 50, 62, 23, 28, 19, 57, 60, 99 };

    List<Integer> foundArray = new ArrayList<Integer>();
    List<Integer> notFoundArray = new ArrayList<Integer>();

    for (int i = 0; i <= originalArray.length; i++) {
        for (int j = 0; j <= keyArray.length; j++) {
            if (originalArray[i] == keyArray[j]) {
                System.out.println("Found");
                foundArray.add(originalArray[i]);
            } else if (originalArray[i] != keyArray[j]) {
                System.out.println("Not Found");
                notFoundArray.add(originalArray[i]);
            }
        }
    }
}

This isn't working.It's giving me ArrayIndexOutOfBoundsException and also executing only else statement.I have googled for it but no correct answer. 这不起作用。它给了我ArrayIndexOutOfBoundsException并且也只执行else语句。我已经用谷歌搜索了它,但没有正确的答案。

Any help is appreciated.Thank you! 感谢您的帮助。谢谢!

Last index of ann array is length-1 because the first index is zero so your code must be ann数组的最后一个索引为length-1因为第一个索引为零,因此您的代码必须为

for (int i = 0; i < originalArray.length; i++) {
    for (int j = 0; j < keyArray.length; j++) {

I suppose that you want to compare input array to array of key, and order is not important. 我想您想将输入数组与键数组进行比较,并且顺序并不重要。

public static void main(String[] args) {

        Set<Integer> originalArray = Arrays.asList(12, 54, 19, 20, 44, 32, 14, 63, 57, 28).stream().collect(Collectors.toSet());
        Set<Integer> keyArray = Arrays.asList(20, 44, 50, 62, 23, 28, 19, 57, 60, 99).stream().collect(Collectors.toSet());

        List<Integer> foundArray = new ArrayList<>();
        List<Integer> notFoundArray = new ArrayList<>();

        for (Integer i : originalArray) {
            if (keyArray.contains(i)) {
                foundArray.add(i);
            } else {
                notFoundArray.add(i);
            }
        }

        System.out.println("Found");
        foundArray.forEach(System.out::println);
        System.out.println("Not found");
        notFoundArray.forEach(System.out::println);
    }

I see two problems with your code. 我发现您的代码有两个问题。 First, your loop bounds are incorrect, because an array of size N can only be addressed up to N-1 . 首先,您的循环边界不正确,因为大小为N的数组最多只能寻址N-1 Second, and perhaps more important, you should do the bookkeeping for each original number after the inner scan loop over the lookup values, not inside it. 其次,也许更重要的是,您应该在内部扫描循环遍历查找值之后而不是在内部对每个原始编号进行簿记。 Taking both of these into account: 考虑到这两个因素:

for (int i=0; i < originalArray.length; i++) {
    boolean found = false;
    for (int j=0; j < keyArray.length; j++) {
        if (originalArray[i] == keyArray[j]) {
            System.out.println("Found");
            found = true;
            break;
        }
    }

    if (found) {
        foundArray.add(originalArray[i]);
    }
    else {
        notFoundArray.add(originalArray[i]);
    }
}

In your current approach, you would be adding the same initial number multiple times to the two collections. 在当前方法中,您将向两个集合多次添加相同的初始编号。 Most likely, you don't want this behavior. 最有可能的是,您不希望出现这种情况。

There are multiple problems (<= instead of < and the logic). 存在多个问题(用<=代替<和逻辑)。 This should work: 这应该工作:

public static void main(String[] args) {

    Integer[] originalArray = { 12, 54, 19, 20, 44, 32, 14, 63, 57, 28 };
    Integer[] keyArray = { 20, 44, 50, 62, 23, 28, 19, 57, 60, 99 };

    List<Integer> foundArray = new ArrayList<Integer>();
    List<Integer> notFoundArray = new ArrayList<Integer>();

    for (int i = 0; i < originalArray.length; i++) {
        boolean found = false;

        for (int j = 0; j < keyArray.length; j++) {
            if (originalArray[i] == keyArray[j]) {
                System.out.println("Found");
                foundArray.add(originalArray[i]);
                found = true;
                break;
            }
        }

        if(found == false) {
            System.out.println("Not Found");
            notFoundArray.add(originalArray[i]);
        }
    }
}
 public static void main(String[] args) {

    Integer[] originalArray = { 12, 54, 19, 20, 44, 32, 14, 63, 57, 28 };
    Integer[] keyArray = { 20, 44, 50, 62, 23, 28, 19, 57, 60, 99 };

    List<Integer> foundArray = new ArrayList<Integer>();
    List<Integer> notFoundArray = new ArrayList<Integer>();

    for (int i = 0; i < originalArray.length; i++) {
        for (int j = 0; j < keyArray.length; j++) {
            if (originalArray[i] == keyArray[j]) {
                System.out.println("Found");
                foundArray.add(originalArray[i]);
            }
        }
    }
}

This won't throw an ArrayOfOfBoundsException and will give you all found elements. 这不会引发ArrayOfOfBoundsException,并且会为您提供所有找到的元素。 To get the unfound elements just take one array and compare it with the ' foundArray '. 要获取未找到的元素,只需获取一个数组并将其与“ foundArray”进行比较。

If you are interessted in a Stream version which just produces the two final lists of integers this code will do it: 如果您对仅生成两个最终整数列表的Stream版本感兴趣,则此代码可以做到:

    Set<Integer> keys = new HashSet<>(Arrays.asList(keyArray));

    Map<Boolean, List<Integer>> partionedIntegers = Arrays.stream(originalArray).collect(Collectors.partitioningBy(keys::contains));
    List<Integer> foundArray = partionedIntegers.get(true);
    List<Integer> notFoundArray = partionedIntegers.get(false);

Please note that this will return two List<Integer> with distinct Integer while the code in the question will result in two lists containing duplicates. 请注意,这将返回两个具有不同Integer List<Integer> ,而问题中的代码将导致两个包含重复项的列表。

More over this code will work with different array lengths. 此代码的更多内容将适用于不同的数组长度。

And referring to my comment on the question: 并参考我对这个问题的评论:
HashSet.contains will use hashCode and equals , not the object identity ( == ) to determine equality. HashSet.contains将使用hashCodeequals ,而不是对象标识( == )确定相等性。

This is also another version using Streams. 这也是使用Streams的另一个版本。

    Integer[] originalArray = { 12, 54, 19, 20, 44, 32, 14, 63, 57, 28 };
    Integer[] keyArray = { 20, 44, 50, 62, 23, 28, 19, 57, 60, 99 };

    List<Integer> foundArray = new ArrayList<>();
    List<Integer> notFoundArray = new ArrayList<>();

    Stream.of(keyArray).forEach(p -> {
            boolean result = Stream.of(originalArray).anyMatch(s -> s.intValue()==p.intValue());
            if(result) {
                foundArray.add(p);
            }else {
                notFoundArray.add(p);
            }
    });

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

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