Is there a concise way to iterate over a stream with indices in Java 8?

后端 未结 22 2744
天命终不由人
天命终不由人 2020-11-22 01:42

Is there a concise way to iterate over a stream whilst having access to the index in the stream?

String[] names = {\"Sam\",\"Pamela\", \"Dave\", \"Pascal\",          


        
22条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 02:06

    If you are trying to get an index based on a predicate, try this:

    If you only care about the first index:

    OptionalInt index = IntStream.range(0, list.size())
        .filter(i -> list.get(i) == 3)
        .findFirst();
    

    Or if you want to find multiple indexes:

    IntStream.range(0, list.size())
       .filter(i -> list.get(i) == 3)
       .collect(Collectors.toList());
    

    Add .orElse(-1); in case you want to return a value if it doesn't find it.

提交回复
热议问题