Answer the question
In order to leave comments, you need to log in
How to find the indexes of duplicate elements in an array?
Hello community. I'm a newbie, so please don't kick too hard.
Let's say we have an integer 5 and a one-dimensional array {1,2,4,5,2,5,7,5,2,8,1}.
The question is, how do I find out the indexes of array elements equal to 5?
upd . Thanks to those who responded, thought and decided.
public static void main(String[] args) {
int a = 5;
int [] array = new int []{1,2,4,5,2,5,7,5,2,8,1};
for(int i = 0; i < array.length; i++){
if(array[i] == a){
System.out.println(i);
}
}
}
Answer the question
In order to leave comments, you need to log in
I won't write the code (you'll have to strain yourself a little), but here's the procedure for you: Cycle through the array starting from the zero element to the last one. Each time get the value from the array at the current loop index. Check this value - is it not a five?. If so then put the current index somewhere. (For a start, you can simply output to the console).
In general, as you wrote above - write at least some code, and we will fix it :)
Write first, what have you already tried to do? Please provide code..
Something like this
int number = 5;
List<Integer> repeatedIndex = new ArrayList<>();
int[] numbers = {1,2,4,5,2,5,7,5,2,8,1};
for(int i = 0; i < numbers.length(); i++)
{
if(numbers[i].equals(number);
{
repeatedIndex.add(i);
}
}
java 8:
public static void main(String[] args) {
int[] array = { 1, 2, 4, 5, 2, 5, 7, 5, 2, 8, 1 };
int[] indices = IntStream.range(0, array.length).filter(i -> array[i] == 5).toArray();
System.out.println(Arrays.toString(indices));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question