How to get findFirst () index 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 this first returned item, since I need to edit it inside the records ArrayList. As far as I know, get()returns the value of the element, not the link. Should i just use

int indexOf(Object o)

instead?

+7
source share
4 answers

You can't just - threads process elements without the context of where they are in the stream.

However, if you are ready to take off your gloves ...

int[] position = {-1};

String firstNotHiddenItem = entries.stream()
        .peek(x -> position[0]++)  // increment every element encounter
        .filter("2"::equals)
        .findFirst()
        .get();

System.out.println(position[0]); // 2

Using int[]instead of simple intallows you to bypass the "effectively final" requirement; the array reference is constant, only its contents change.

"2"::equals e β†’ e.equals("2"), NPE ( null), , , .


( ) :

AtomicInteger position = new AtomicInteger(-1);

String firstNotHiddenItem = entries.stream()
        .peek(x -> position.incrementAndGet())  // increment every element encounter
        .filter("2"::equals)
        .findFirst()
        .get();

position.get(); // 2
+5

IntStream like:

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

List::indexOf, , , .

+7

Eclipse Collections Java 8

int firstIndex = ListIterate.detectIndex(entries, "2"::equals);

MutableList, :

MutableList<String> entries = Lists.mutable.with("0", "1", "2", "3");
int firstIndex = entries.detectIndex("2"::equals);

.

int lastIndex = entries.detectLastIndex("2"::equals);

: Eclipse

0

, indexOf("2"). , , .

, , . map.entrySet().stream().filter(e -> e.getKey().equals(object)).map(e -> e.getValue()) map.get(object).

, . .

, , , , Stream API . " Java 8?", , , , IntStream.range List.get(int). List, . .

0

Source: https://habr.com/ru/post/1677569/


All Articles