简体   繁体   中英

Find indices of the same elements in an array without loop

Suppose that I've the following array:

arr = [T, F, F, T, F, F, F, T, F];

Is there an easy way to find indices of T 's? I'd like to return [0,3,7] in this case and don't want to use any loop.

I've searched a solution on the net but couldn't find anything.

List<String> list = Arrays.asList("T", "F", " F", "T", "F", "F", "F", "T", "F");
        String looking_for = "T";
        int[] indices = 
                IntStream.range(0, list.size())
                .filter(i -> list.get(i).equals(looking_for)).toArray();
        System.out.printf("Indices with %s are %s%n", looking_for, Arrays.toString(indices));

Output:

Indices with T are [0, 3, 7]

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