查找' x'的所有索引在ArrayList中

时间:2017-12-03 20:03:58

标签: java arraylist

我试图在ArrayList中搜索用户输入。我设法创建了一个搜索,从阵列中打印出第一个匹配项的索引。

我在尝试获取项目x的其余索引时遇到问题。

以下是我到目前为止打印search的第一个索引的代码:

if (name.contains(search))
{
    System.out.println("name found!");
    System.out.println(name.indexOf(search));
}

我知道需要添加一个循环。但我在制定它时遇到了麻烦。

示例数据

ArrayList<String> author = new ArrayList<String>();
name.add("Bob");
name.add("Jerry");
name.add("Bob"); 
name.add("Mick");               

search = "Bob"

我的预期结果是0,2

相反,我只能打印第一个匹配项(0)。

3 个答案:

答案 0 :(得分:0)

您可以浏览整个列表并保存与搜索词匹配的所有索引。 Java 8的流程为您提供了一种非常优雅的方式:

int[] indexes =
    IntStream.range(0, author.size())
             .filter(i -> author.get(i).equals(searchTerm))
             .toArray();

答案 1 :(得分:0)

说明

方法List#indexOf仅返回第一个找到的匹配元素的索引。来自documentation

  

返回此列表中第一次出现的指定元素的索引,如果此列表不包含该元素,则返回-1。 [...]

但是你想要所有,因此你还需要迭代所有元素

另请注意,由于List#contains也回答了此问题,因此无需调用List#indexOf,如果找不到,则会返回-1。实际上在ArrayList中,两个调用都非常昂贵(它们从左到右迭代直到找到)所以如果它们非常昂贵,就不应该使用不必要的语句。

解决方案

相反,只需迭代所有元素并收集匹配的元素:

ArrayList<String> author = ...
String needle = ...

// Collect matches
List<Integer> matchingIndices = new ArrayList<>();
for (int i = 0; i < author.size(); i++) {
    String element = author.get(i);

    if (needle.equals(element)) {
        matchingIndices.add(i);
    }
}

// Print matches
matchingIndices.forEach(System.out::println);

或者您可以使用 Stream API 的一些非常方便的方法。 Stream#filterdocumentation)例如:

List<Integer> matchingIndices = IntStream.range(0, author.size())
    .filter(i -> needle.equals(author.get(i))) // Only keep those indices
    .collect(Collectors.toList());

答案 2 :(得分:0)

for (int i = 0;i<author.size();i++){
  if(author.get(i).equals(searchTerm)) {
    System.out.println("Author found!");
    System.out.println(i);
  }
}
相关问题