Второй раз встречается задача. Нужно вывести первый не повторяющейся элемент. Ниже 2 норм решения.
public static void main(String[] args) {
int[] arr1 = {9, 4, 9, 5, 4, 5};
int[] arr2 = {9, 4, 9, 6, 7, 4, 5};
int[] arr3 = new int[]{0, 0, -7, -7, -7, 1, 2, 5, 3, 1, 2};
public static int findFirstUniqueElement(int[] arr) {
return Arrays.stream(arr)
.filter(num -> Arrays.stream(arr)
.filter(innerNum -> innerNum == num)
.count() == 1)
.findFirst()
.orElse(-1);
}
private static int getFirstUnique(int[] arr) {
LinkedHashMap map = Arrays.stream(arr)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
return map.entrySet().stream()
.filter(x -> x.getValue() == 1)
.findFirst()
.orElseThrow(() -> new RuntimeException("Элемент не найден"))
.getKey();
}
private static int getFirstUnique2(int[] arr) {
Map seen = new HashMap<>();
Set uniqueElements = new LinkedHashSet<>();
for (int num : arr) {
if (seen.containsKey(num)) {
uniqueElements.remove(num);
} else {
seen.put(num, true);
uniqueElements.add(num);
}
}
if (!uniqueElements.isEmpty()) {
return uniqueElements.iterator().next();
} else {
return -1;
}
}