adfgvx
adfgvx

Reputation: 51

select first index in collection where like

I feel sometimes that I'm reinventing the wheel.

I'm wondering if there are any utility methods in java/jakarta commons/guava/?, that will go deeper in the collection and do something (test, modify, remove) with the elements.

I wrote this method and now I feel that there is some one-liner that can do it.

/**
 * 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;
}

Upvotes: 3

Views: 1394

Answers (2)

mergeconflict
mergeconflict

Reputation: 8276

Guava has what you want in Iterables.indexOf(), although I wouldn't exactly argue that it'll make your code more readable:

public static int findIdx(List<String> list, final String search) {
  return Iterables.<String> indexOf(list, new Predicate<String>() {
    public boolean apply(String s) {
      return s.contains(search);
    }
  });
}

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1502076

Guava has Iterables.indexOf with a predicate:

int index = Iterables.indexOf(list, new Predicate<String> {
        @Override public boolean apply(String input) {
            return input.contains(search);
        }
    });

Not much better, admittedly - and you need to make search final. But at least with Java 8 you'll be able to write something like:

int index = Iterables.indexOf(list, input => input.contains(search));

(Or at least something like that. And possibly in an extension method syntax...)

Upvotes: 5

Related Questions