new2Activity21
new2Activity21

Reputation: 13

List<Character> how to get specific index?

How can I get a specific index in the List if it has only the methods for the first and last element, when the element in the list repeats several times?

List<Character> listString = new ArrayList<>();

listString.add(0, 'A');
listString.add(1, 'A');
listString.add(2, 'A');
listString.add(3, 'A');


int index = listString.indexOf('A');
int indexLast = listString.lastIndexOf('A');

System.out.println(index);
System.out.println(indexLast);

Output:

0

3

So how can I get information that 'A' is also in index 1 and 2?

Upvotes: 1

Views: 471

Answers (2)

FNZ
FNZ

Reputation: 27

You can print your answers out like this (after writing the above code):

for (int i = 0; i <indices.size() ; i++) {
        System.out.println(indices.get(i));
    }

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56423

use a typical for loop:

List<Integer> indices = new ArrayList<>();
for (int i = 0; i < listString.size(); i++) 
     if(listString.get(i) == 'A')
        indices.add(i);

or:

int[] indices = IntStream.range(0, listString.size())
                         .filter(i -> listString.get(i) == 'A')
                         .toArray();

Upvotes: 2

Related Questions