Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get index of findFirst() in java 8?

I have the following code:

ArrayList <String> entries = new ArrayList <String>();

entries.add("0");
entries.add("1");
entries.add("2");
entries.add("3");

String firstNotHiddenItem = entries.stream()
                    .filter(e -> e.equals("2"))
                    .findFirst()
                    .get();

I need to know what is the index of that first returned element, since I need to edit it inside of entries ArrayList. As far as I know get() returns the value of the element, not a reference. Should I just use

int indexOf(Object o)

instead?

like image 912
Andrei Avatar asked May 19 '17 19:05

Andrei


People also ask

What does findFirst () do in Java?

The findFirst() method finds the first element in a Stream. So, we use this method when we specifically want the first element from a sequence. When there is no encounter order, it returns any element from the Stream. According to the java.

How do you get index of the list Java?

The standard solution to find the index of an element in a List is using the indexOf() method. It returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.

What's the difference between findFirst () and findAny ()?

Java 8 Stream findFirst() and findAny() In Java 8 Stream, the findFirst() returns the first element from a Stream, while findAny() returns any element from a Stream.


Video Answer


1 Answers

You can get the index of an element using an IntStream like:

int index = IntStream.range(0, entries.size())
                     .filter(i -> "2".equals(entries.get(i)))
                     .findFirst().orElse(-1);

But you should use the List::indexOf method which is the preferred way, because it's more concise, more expressive and computes the same results.

like image 58
Flown Avatar answered Oct 14 '22 08:10

Flown