Jua*_*des 2 java collections list indexof
是否有内置方法来搜索java.util.List,指定从中开始搜索的第一个项目?就像你可以用字符串一样
我知道我可以自己轻松实现一些东西,但是如果是Java或者http://commons.apache.org/collections/api-release/org/apache/commons/collections/package-summary我宁愿不重新发明轮子..html已经拥有它.
我不是问如何实现这个,我在问是否已经有了什么东西这里的很多建议都是错误的.
如果有人关心获得正确答案的信用,请更新您的答案,说没有内置的方法(如果您确切知道)
这就是我想做的事情
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);
Run Code Online (Sandbox Code Playgroud)
现在我正在使用
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
我也把它实现为
public static int indexOf(List<?> list, Object toFind, int startingIndex) {
int index = list.subList(startingIndex).indexOf(toFind);
return index == -1 ? index : index + startingIndex;
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*der 13
不是一个单一的方法,但有一个简单的记录方法,使用1-2行代码.它甚至在这个方法的文档中这样说:
strings.subList(5, strings.size()).indexOf("someValue");
Run Code Online (Sandbox Code Playgroud)
可能会在结果中添加5(如果不是-1),具体取决于您是否要保留该子列表等:
int result = list.subList(startIndex, list.size()).indexOf(someValue);
return result== -1 ? -1 : result+startIndex;
Run Code Online (Sandbox Code Playgroud)
注:
subList没有没有建立一个新的List,只是一个视图到原来的一个.