I’ve got the following Java code but List.indexOf() seems to do pretty much the same thing (including returning -1 if not found. Is there any way of passing indexOf() an Object that expresses the idea that the object is not 0?
/**
* Find the first non-zero element in a List of Integers
* @param row List of Integers
* @return -1 if all zeros in row
* otherwise position of first non zero element
*/
public static int leading(List<Integer> row) {
for (int i = 0; i < row.size(); i++) {
if (row.get(i)!= 0) {
return i;
}
}
return -1;
}
Re: Thorbjørn Ravn Andersen: If I passed in null into IndexOf() it will always return -1 because my list always contains Integers. I want to do something like row.indexOf(Integer a where !a.equals(0)). Not sure if possible
List.indexOf"solution"List.indexOf(Object o)is defined as follows:It is tempting to try to give a "meta" element object that is not really in the
List, and may not even be of the same type as the actual elements of theList, and yet isequalsto some desired element based on a predicate. This should work, sinceindexOfis defined in terms of the givenObject o‘sequalsmethod against an element in the list (and not the other way around), but is a really "hacky" way of achieving what you want.Here’s a proof of concept:
The "meta" element object is
equalsto any negativeInteger, and yet noIntegercan ever beequalsto it. This asymmetry is a gross violation of theequalscontract, but it "works" nonetheless.Guava solution
A much better solution that conveys the intent is using Guava’s higher-order functions. Here’s one from
com.google.commons.collect.Iterables:Snippet
Here’s a snippet to illustrate the expressive power of Guava’s higher-order functions:
Summary
List.indexOf(Object)can be abused to find elements that satisfy a given predicate, but this is a violation theequalscontractPredicateand higher-order functions likeindexOf,find,filter,all,anyetc allows you to express these operations in a much more powerfully expressive ways