检索包含值的所有项的索引

时间:2017-06-15 06:26:06

标签: java

我需要获取所有索引编号,我将获得关键字'文章'的匹配。 &安培;我也想要反击' indexoccurencecounter'只有在我得到一场比赛时才能增加。

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

1 个答案:

答案 0 :(得分:2)

由于多个索引匹配,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.