简体   繁体   中英

How can I use the index in my array list and convert to int?

I am struggling using the indexes of the elements in my array and convert it to int.

I can't find something useful on google.

For example, I have a string array A [] = {apple, banana, cat}

and then I want the indexes of each element to be an integer like this and is stored in an int array a [] = {0, 1, 2}

You can use IntStream.range :

int[] indexes = IntStream.range(0, array.length).toArray();

Welcome to SO Stefaney.

You can do like this:

int[] indexes = new int[array.length];
Arrays.setAll(indexes, i -> i);

You can do it using a for loop:

int[] indexes = new int[array.length];
for (int i = 0; i < array.length; i++) {
    indexes[i] = i;
}

However, I think @iota's is a more elegant answer, using IntStream .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM