[英]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
0
3
3
So how can I get information that 'A' is also in index 1 and 2? 那么,如何获得索引1和2中也包含“ A”的信息?
use a typical for loop: 使用典型的for循环:
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();
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.