简体   繁体   中英

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 ).

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.

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

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 . 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. To get the unfound elements just take one array and compare it with the ' foundArray '.

If you are interessted in a Stream version which just produces the two final lists of integers this code will do it:

    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.

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.

This is also another version using 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);
            }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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