Senior
Java task: given an int[] array, form two lists — only unique and only duplicates.
sobes.tech AI
Answer from AI
To split an int[] array into lists of unique elements and duplicates, you can use a HashMap to count occurrences:
import java.util.*;
public class UniqueAndDuplicates {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 4, 5, 5, 6};
Map<Integer, Integer> counts = new HashMap<>();
for (int num : arr) {
counts.put(num, counts.getOrDefault(num, 0) + 1);
}
List<Integer> unique = new ArrayList<>();
List<Integer> duplicates = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
if (entry.getValue() == 1) {
unique.add(entry.getKey());
} else {
duplicates.add(entry.getKey());
}
}
System.out.println("Unique: " + unique);
System.out.println("Duplicates: " + duplicates);
}
}
In this example, we first count the occurrences of each number, then create two lists: one with elements that occur once, and another with repeating elements.