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

后端 未结 22 2308
天命终不由人
天命终不由人 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 01:49

    This question (Stream Way to get index of first element matching boolean) has marked the current question as a duplicate, so I can not answer it there; I am answering it here.

    Here is a generic solution to get the matching index that does not require an external library.

    If you have a list.

    public static  int indexOf(List items, Predicate matches) {
            return IntStream.range(0, items.size())
                    .filter(index -> matches.test(items.get(index)))
                    .findFirst().orElse(-1);
    }
    

    And call it like this:

    int index = indexOf(myList, item->item.getId()==100);
    

    And if using a collection, try this one.

       public static  int indexOf(Collection items, Predicate matches) {
            int index = -1;
            Iterator it = items.iterator();
            while (it.hasNext()) {
                index++;
                if (matches.test(it.next())) {
                    return index;
                }
            }
            return -1;
        }
    

提交回复
热议问题