Detailed explanation of five classic Java array deduplication algorithms
In Java programming, we often encounter situations where we need to perform deduplication operations on arrays, that is, remove arrays Duplicate elements in , retain unique elements. The following will introduce five classic Java array deduplication algorithms and provide corresponding code examples.
import java.util.Arrays; import java.util.HashSet; public class ArrayDeduplicateExample { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 3, 5}; HashSet<Integer> set = new HashSet<>(); for (int i : array) { set.add(i); } int[] result = new int[set.size()]; int index = 0; for (int i : set) { result[index++] = i; } System.out.println(Arrays.toString(result)); } }
import java.util.Arrays; import java.util.TreeSet; public class ArrayDeduplicateExample { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 3, 5}; TreeSet<Integer> set = new TreeSet<>(); for (int i : array) { set.add(i); } Integer[] result = set.toArray(new Integer[0]); int[] deduplicatedArray = Arrays.stream(result).mapToInt(Integer::intValue).toArray(); System.out.println(Arrays.toString(deduplicatedArray)); } }
import java.util.Arrays; public class ArrayDeduplicateExample { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 3, 5}; int[] deduplicatedArray = Arrays.stream(array).distinct().toArray(); System.out.println(Arrays.toString(deduplicatedArray)); } }
import java.util.Arrays; public class ArrayDeduplicateExample { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 3, 5}; for (int i = 0; i < array.length - 1; i++) { if (array[i] != Integer.MIN_VALUE) { for (int j = i + 1; j < array.length; j++) { if (array[i] == array[j]) { array[j] = Integer.MIN_VALUE; } } } } int count = 0; for (int i = 0; i < array.length; i++) { if (array[i] != Integer.MIN_VALUE) { array[count++] = array[i]; } } int[] deduplicatedArray = Arrays.copyOf(array, count); System.out.println(Arrays.toString(deduplicatedArray)); } }
import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class ArrayDeduplicateExample { public static void main(String[] args) { int[] array = {1, 2, 3, 2, 4, 3, 5}; Map<Integer, Object> map = new HashMap<>(); for (int i : array) { map.put(i, null); } int[] deduplicatedArray = new int[map.size()]; int index = 0; for (int i : map.keySet()) { deduplicatedArray[index++] = i; } System.out.println(Arrays.toString(deduplicatedArray)); } }
The above are detailed introductions and code examples of five classic Java array deduplication algorithms. In practical applications, choosing an appropriate deduplication algorithm according to specific circumstances can improve the performance and readability of the program.
The above is the detailed content of Detailed explanation of five classic Java array deduplication algorithms. For more information, please follow other related articles on the PHP Chinese website!