3 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超2個(gè)贊
你需要 :
迭代值
檢查長(zhǎng)度
如果條件通過(guò),則保留索引
Workable demo
:使用Streams
您可以內(nèi)聯(lián)解決方案以獲得一個(gè)List
或一個(gè)int[]
List<Integer> indexes = values.stream().filter(s -> s.length() == 4)
.map(values::indexOf)
.collect(Collectors.toList());
int[] indexesArray = values.stream().filter(s -> s.length() == 4)
.mapToInt(values::indexOf)
.toArray();
Workable demo
:使用經(jīng)典for loop
List<Integer> indexes = new ArrayList<>();
for(int i=0; i<values.size(); i++){
if(values.get(i).length() == 4){
indexes.add(i);
}
}

TA貢獻(xiàn)1111條經(jīng)驗(yàn) 獲得超0個(gè)贊
您可以創(chuàng)建一個(gè)IntStream
索引:
IntStream allIndices = IntStream.range(0, values.size());
然后您可以根據(jù)您提供的條件進(jìn)行過(guò)濾:
IntStream filteredIndices = allIndices.filter(i -> values.get(i).length() == 4);
最后,您可以將這些索引轉(zhuǎn)換為您喜歡的任何數(shù)據(jù)結(jié)構(gòu)。
數(shù)組:
int[] indices = filteredIndices.toArray();
或者一個(gè)列表
List<Integer> indices = filteredIndices.boxed().collect(Collectors.toList());
作為一個(gè)聲明:
int[] indices = IntStream.range(0, values.size()) .filter(i -> values.get(i).length() == 4) .toArray();
添加回答
舉報(bào)