查找列表中某个值的所有索引 [英] Find all indexes of a value in a List

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

问题描述

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

我在尝试获取存储该项目的其余索引时遇到问题.

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

if (names.contains(search)) {System.out.println(找到名字!");System.out.println(names.indexOf(search));}

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

示例

ArrayList名称 = 新的 ArrayList();names.add(鲍勃");names.add(杰瑞");names.add(鲍勃");names.add(Mick");

search = Bob".我的预期结果是 {0,2}.相反,我只能获得第一次出现的索引 (0).

assert allIndexesOf(names, "Bob").equals(List.of(0, 2));[...]私人列表<整数>allIndexesOf(List list, Object o) {//如何实现?}

如何获取与搜索字符串匹配的所有索引?

解决方案

说明

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

<块引用>

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

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

还要注意,调用 List#contains 不是必要的,因为 List#indexOf 也回答了这个问题,如果没有找到它返回 -1.事实上,在 ArrayList 中,两个调用都非常昂贵(它们从左到右迭代直到找到)所以如果它们如此昂贵,你不应该使用不必要的语句.><小时>

解决方案

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

ArrayList作者 = ...线针= ...//收集匹配列表<整数>匹配索引 = 新的 ArrayList<>();for (int i = 0; i < author.size(); i++) {字符串元素 = author.get(i);如果(needle.equals(元素)){matchIndices.add(i);}}//打印匹配matchIndices.forEach(System.out::println);

或者您可以使用Stream API的一些非常方便的方法.Stream#filter(文档) 例如:

ListmatchIndices = IntStream.range(0, author.size()).filter(i ->needle.equals(author.get(i)))//只保留那些索引.collect(Collectors.toList());

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 list.

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

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

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

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

Example

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

Say search = "Bob". My expected result would be {0,2}. Instead, I am only able to get the index of the first occurrence (0).

assert allIndexesOf(names, "Bob").equals(List.of(0, 2));

[...]

private List<Integer> allIndexesOf(List<?> list, Object o) {
  // How can this be implemented?
}

How can I get all indexes that match the search string?

解决方案

Explanation

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

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.

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.


Solution

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);

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());

这篇关于查找列表中某个值的所有索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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