gpt4 book ai didi

java - 检索包含某个值的所有项目的索引

转载 作者:行者123 更新时间:2023-12-02 02:46:05 25 4
gpt4 key购买 nike

我需要获取所有索引号,我将获得关键字“Articles”的匹配,而且我希望计数器“indexoccurrencecounter”仅在获得匹配时才会递增。

List<String> valueslist = new ArrayList<String>();
valueslist.add("Articles");
valueslist.add("Vals");
valueslist.add("Articles");
valueslist.add("Toast");

String key="Articles";

System.out.println("List contents having values are: "+valueslist);
int ind=0;
int indexoccurencecounter=0;
for (int i=0;i<valueslist.size();i++){
ind=valueslist.indexOf(key);
if (ind>=0){
indexoccurencecounter++;
}
}
System.out.println("Index's of the key "+key+" is: "+ind);
System.out.println("The key specified appears "+indexoccurencecounter+" times in the result links");

我的上面的代码给了我不正确的输出,我期望输出如下:

List contents having values are: [Articles, Vals, Articles, Toast]
Index's of the key Articles is: 0,2
The key specified appears 2 times in the result links

最佳答案

因为多个索引会匹配,int ind无法跟踪所有这些。它只能追踪一个。我建议您创建一个 List<Integer>的指数。这样做的一个有用的副作用是您不再需要计算出现次数 - 您可以简单地使用 size()列表的方法。

List<String> values = new ArrayList<>();
values.add("Articles");
values.add("Vals");
values.add("Articles");
values.add("Toast");

String searchTerm = "Articles";

List<Integer> matchingIndices = new ArrayList<>();

for (int i = 0; i < values.size(); i++) {
String candidate = values.get(i);
if (candidate.indexOf(searchTerm) >= 0) {
matchingIndices.add(i);
}
}

int numberOfMatches = matchingIndices.size();

System.out.println("Values: " + values);
System.out.println("Indexes of the key '" + searchTerm + "': " + matchingIndices);
System.out.println("The key appears " + numberOfMatches + " times.");

产品:

Values: [Articles, Vals, Articles, Toast]
Indexes of the key 'Articles': [0, 2]
The key appears 2 times.

关于java - 检索包含某个值的所有项目的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44560101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com