1

I have a list of object and I want to find the index of an element with a specific attribute value.

Such as

List<MyObject> objects = // some objects;

int indexOfFirstDVD = someUtils.findIndex(objects, obj -> "DVD".equals(obj.getType()));

I know it's easy to write one with a for-loop, but is there any existing simple way to do that, such as streaming or any library utils?

Lan Tian
  • 31
  • 5
  • 2
    Do you want to learn the [stream API](https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html)? There is already a method in the `java.util.List` interface that returns the index of an object in the list, namely [`indexOf(Object)`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#indexOf-java.lang.Object-) – Abra Apr 17 '20 at 07:04
  • 2
    This question already has answer here https://stackoverflow.com/questions/38963338/stream-way-to-get-index-of-first-element-matching-boolean – Michal Apr 17 '20 at 07:22
  • If you have an ArrayList you can use arrayListObject.indexOf(dvd) https://www.geeksforgeeks.org/java-util-arraylist-indexof-java/ – armin.miedl Apr 17 '20 at 07:28
  • Thanks @Michal that's what I was looking for! `list.indexOf(object)` is not good enough because I want to customize the search function. I also like the answer from @davidgiga1993. – Lan Tian Nov 18 '21 at 09:38

1 Answers1

2

You can do that using IntStream

OptionalInt result = IntStream.range(0, objects.size())
                .filter(x -> "DVD".equals(objects.get(x)))
                .findFirst();

if (result.isPresent())
{
   int index = result.getAsInt();
}

davidgiga1993
  • 2,695
  • 18
  • 30