Java中如何获取数组中重复元素的所有索引位置?
Absolutely! Finding all occurrences of a value (including duplicates) and their indices in a Java array is totally achievable. It sounds like your initial loop might have been terminating early after finding the first match—let's fix that with a couple of straightforward solutions.
Solution 1: Traditional For Loop
This is the most basic and widely compatible approach, working in all Java versions. We'll iterate through every index of the array, check if the element at that index matches our target value, and collect the matching indices into a list.
import java.util.ArrayList; import java.util.List; public class FindIndices { public static void main(String[] args) { Double[] array = {100.0, 200.0, 300.0, 400.0, 500.0, 100.0}; double target = 100.0; List<Integer> indices = new ArrayList<>(); for (int i = 0; i < array.length; i++) { // For exact double matches, equals() is safer than == for object types if (array[i].equals(target)) { indices.add(i); } } System.out.println("Indices of " + target + ": " + indices); // Output: Indices of 100.0: [0, 5] } }
Key Notes:
- We use
array[i].equals(target)instead of==for Double objects to avoid potential issues with object references (though for autoboxed primitive values like 100.0,==might work here,equals()is the safer practice). - If you're working with non-exact floating-point values (e.g., 0.1), compare using a small tolerance:
Math.abs(array[i] - target) < 1e-9to account for precision errors.
Solution 2: Java Streams (Java 8+)
If you prefer a more concise, functional approach, Java Streams make this easy. We can generate a stream of indices, filter those where the element matches the target, and collect the results into a list.
import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class FindIndicesWithStreams { public static void main(String[] args) { Double[] array = {100.0, 200.0, 300.0, 400.0, 500.0, 100.0}; double target = 100.0; List<Integer> indices = IntStream.range(0, array.length) .filter(i -> array[i].equals(target)) .boxed() .collect(Collectors.toList()); System.out.println("Indices of " + target + ": " + indices); // Output: Indices of 100.0: [0, 5] } }
How This Works:
IntStream.range(0, array.length)creates a stream of integers from 0 to the last index of the array.filter(i -> array[i].equals(target))keeps only the indices where the element matches our target.boxed()converts the primitiveintstream to a stream ofIntegerobjects.collect(Collectors.toList())gathers the matching indices into a list.
Both solutions will correctly identify that the value 100.0 is at indices 0 and 5 in your example array. The traditional loop is great for readability and compatibility, while streams offer a more modern, concise syntax.
内容的提问来源于stack exchange,提问作者George Wang

