在ArrayList中找到'x'的所有索引 [英] Find all indexes of 'x' in ArrayList

查看:144
本文介绍了在ArrayList中找到'x'的所有索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ArrayList中搜索用户输入.我设法创建了一个搜索,该搜索从Array中打印出第一次出现的索引.

I'm trying to search an ArrayList for a user input. I've managed to create a search that prints the index of the first occurrence from within the Array.

我在尝试获取存储项目x的其余索引时遇到麻烦.

I'm having trouble trying to get the rest of the indexes that item x are stored.

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

Here is the code I have got so far to print the first index of search:

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

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

I understand that a loop needs to be added. But I am having trouble trying to formulate it.

样本数据

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

search = "Bob"

我的预期结果是0,2.

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

Instead, I am only able to print the first occurrence (0).

推荐答案

说明

方法List#indexOf仅返回找到的第一个匹配元素的索引.从其文档中:

Explanation

The method List#indexOf only returns the index of the first found matching element. From its documentation:

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

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. [...]

但是您要全部,因此还需要重复所有元素.

But you want all, therefore you also need to iterate all elements.

还请注意,不必调用List#contains,因为List#indexOf也会回答此问题,如果未找到,则会返回-1.实际上,在ArrayList中,两个调用都非常昂贵(它们从左到右进行迭代直到找到),因此如果它们如此昂贵,则不应使用不必要的语句.

Also note that calling List#contains is not necessary since List#indexOf also answers this question, it returns -1 if not found. In fact in an ArrayList both calls are very expensive (they iterate from left to right until found) so you shouldn't use unnecessary statements if they are such expensive.

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

Instead just iterate all elements and collect the ones that match:

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#filter(

Or you may use some of the very convenient methods of the Stream API. Stream#filter (documentation) for example:

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

这篇关于在ArrayList中找到'x'的所有索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆