Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Java

Idiom #222 Find the first index of an element in list

Set i to the first index in list items at which the element x can be found, or -1 if items does not contain x.

int i = -1;
for(int j=0;j<items.length;j++){
	if(items[j].equals(x)){
		i = j;
		break;
	}
}

The .equals() method equates objects.

If equating primitives you would use the “x == y” expression
int i = items.indexOf​(x);
(defn find-index [x items]
  (or (->> items
           (map-indexed vector)
           (filter #(= x (peek %)))
           ffirst)
      -1))

New implementation...
programming-idioms.org