Java – select the first index in the collection
•
Java
I sometimes feel like I'm reinventing the wheel
I want to know in Java / Jakarta commons / guava /? Whether there are any utility methods in the collection, which will go deeper in the collection and use elements to perform certain operations (test, modify, delete)
I wrote this method, and now I think there are some one-way trips that can be done
/**
* Find index of first line that contains search string.
*/
public static int findIdx(List<String> list,String search) {
for (int i = 0,n = list.size(); i < n; i++)
if (list.get(i).contains(search))
return i;
return -1;
}
Solution
Guava has an iterables with predicates indexOf:
int index = Iterables.indexOf(list,new Predicate<String> {
@Override public boolean apply(String input) {
return input.contains(search);
}
});
Admittedly, it's not better - and you need to search for the final But at least in Java 8, you will be able to write the following:
int index = Iterables.indexOf(list,input => input.contains(search));
(or at least something similar. Maybe in the extension method syntax...)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
