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

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

    Just for completeness here's the solution involving my StreamEx library:

    String[] names = {"Sam","Pamela", "Dave", "Pascal", "Erik"};
    EntryStream.of(names)
        .filterKeyValue((idx, str) -> str.length() <= idx+1)
        .values().toList();
    

    Here we create an EntryStream which extends Stream> and adds some specific operations like filterKeyValue or values. Also toList() shortcut is used.

提交回复
热议问题