-1

I have two int Arrays:

int[] first = new int[]{1, 4, 5};

int[] second = new int[]{9, 7, 1, 5, 5};

I need to get elements that are not present in each of the arrays. Result: 9, 7, 4

I can get this result as follows:

    int[] first = new int[]{1, 4, 5};
    int[] second = new int[]{9, 7, 1, 5, 5};

    Set<Integer> firstSet = Arrays.stream(first).boxed().collect(Collectors.toSet());
    Set<Integer> secondSet = Arrays.stream(second).boxed().collect(Collectors.toSet());

    Set<Integer> result = new HashSet<>();

    Arrays.stream(first).forEach(v -> {
        if (!secondSet.contains(v)) {
            result.add(v);
        }
    });
    Arrays.stream(second).forEach(v -> {
        if (!firstSet.contains(v)) {
            result.add(v);
        }
    });

    result.forEach(System.out::println);

How to get this result more correctly?

1 Answers1

0

You can do it as follows:

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        int[] first = new int[] { 1, 4, 5 };
        int[] second = new int[] { 9, 7, 1, 5, 5 };
        Set<Integer> firstSet = Arrays.stream(first).boxed().collect(Collectors.toSet());
        Set<Integer> secondSet = Arrays.stream(second).boxed().collect(Collectors.toSet());
        Set<Integer> firstSetCopy = new HashSet<>(firstSet);

        firstSet.removeAll(secondSet);
        secondSet.removeAll(firstSetCopy);

        Set<Integer> result = new HashSet<>();
        result.addAll(firstSet);
        result.addAll(secondSet);

        System.out.println(result);
    }
}

Output:

[4, 7, 9]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110