搜索从特定索引开始的java.util.List [英] Search a java.util.List starting at a specific index

查看:62
本文介绍了搜索从特定索引开始的java.util.List的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在用于搜索java.util.List的内置方法,该列表指定了从中开始搜索的第一项?就像您可以使用

Is there a built-in method to search a java.util.List specifying the first item to start the search from? Like you can do with Strings

我知道我可以轻松地自己实现某些功能,但是如果Java或

I know I can easily implement something on my own, but I'd rather not reinvent the wheel if Java or http://commons.apache.org/collections/api-release/org/apache/commons/collections/package-summary.html already has it.

我不是在问如何实现它,而是在问是否已有可用的东西.这里的很多建议都是错误的.

I'm not asking how to implement this, I'm asking whether something is already available A lot of the suggestions here were buggy.

如果有人希望获得正确答案的信用,请更新您的答案以说没有内置的方法(如果您确定的话)

这就是我想做的

List<String> strings = new ArrayList<String>();
// Add some values to the list here
// Search starting from the 6th item in the list
strings.indexOf("someValue", 5);

现在我正在使用

/**
 * This is like List.indexOf(), except that it allows you to specify the index to start the search from
 */
public static int indexOf(List<?> list, Object toFind, int startingIndex) {
    for (int index = startingIndex; index < list.size(); index++) {
        Object current = list.get(index);
        if (current != null && current.equals(toFind)) {
            return index;
        }
    }
    return -1;
}

我也将其实现为

public static int indexOf(List<?> list, Object toFind, int startingIndex) {
    int index = list.subList(startingIndex).indexOf(toFind);
    return index == -1 ? index : index + startingIndex;
}

推荐答案

不是一个单一的方法,但是有一个简单的文档记录的方法来处理1-2行代码.它甚至说在此方法的文档中:

No not a single method, but there is a simple documented way of doing this with 1-2 lines of code. It even says so in the documentation for this method:

strings.subList(5, strings.size()).indexOf("someValue");

可能要在结果中添加5(如果不是-1),具体取决于您是否希望将该子列表保留在周围,等等:

Possibly add 5 to the result (if not -1), depending on if you want to keep that sublist around or not etc:

int result = list.subList(startIndex, list.size()).indexOf(someValue);
return result== -1 ? -1 : result+startIndex;

注意: subList 不会创建新的 List ,只是原始视图的一个视图.

Note: subList does not create a new List, just a view into the original one.

这篇关于搜索从特定索引开始的java.util.List的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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