Home > Software design >  How to display the index for multiple elements with same value in an array list
How to display the index for multiple elements with same value in an array list

Time:11-07

Can't printout the indexes for all the elements with the same value from an array list. Only the index for the first element found in the array list is printed out.

Current output when list = 5,5,4,5: Number 5 can be found in the following indexes [0, 0, 0, 0]

The desired output would be: Number 5 can be found in the following indexes [0, 1, 3]

How I would want the code to work is that the user has to enter integers to an array list until the value -1 is entered. After that system prints out "What number are you looking for?". User enters the number for the element(s) that is wanted to be fetched from the array list. After that system prints out "Number 5 can be found in the following indexes [0, 1, 3].

Here's my code so far:

import java.util.ArrayList;
import java.util.Scanner;

public class sandbox{
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        ArrayList<Integer> list = new ArrayList<>();
        while (true) {
            int read = Integer.valueOf(reader.nextLine());
            if (read == -1) {
                break;
            }

            list.add(read);
        }
        System.out.print("What number are you looking for? ");
        int requestednumb = Integer.valueOf(reader.nextLine());
        int count = 0;

        ArrayList<Integer> index = new ArrayList<>();
        while ((list.size() > count)) {
            if (list.contains(requestednumb))
                ;
            index.add(list.indexOf(requestednumb));
            count  ;
        }
        System.out.println("Number "   requestednumb   " can be found in the following indexes "   index);
    }

}

`

I'm pretty sure that it's an silly beginner mistake I have made, but after being stuck with this problem for multiple hours, I hope you can find the time to help me with this.

CodePudding user response:

Use for loop to change the index and check the number at the given index:

for (int i = 0, n = list.size(); i < n; i  ) {
    if (list.get(i) == requestednumb) { // check the number at index i
        index.add(i); // store the index
    }
}

Or, with while loop and count used as the index:

int count = 0;

ArrayList<Integer> index = new ArrayList<>();
while (count < list.size()) {
    if (list.get(count) == requestednumb) {
        index.add(count);
    }
    count  ;
}

CodePudding user response:

Try this.

static <T> List<Integer> findIndices(List<T> list, T key) {
    return IntStream.range(0, list.size())
        .filter(i -> list.get(i).equals(key))
        .boxed().toList();
}

public static void main(String[] args) {
    List<Integer> list = List.of(5, 5, 4, 5);
    System.out.println(findIndices(list, 5));
}

output:

[0, 1, 3]
  • Related