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

后端 未结 22 2346
天命终不由人
天命终不由人 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 02:10

    You can create a static inner class to encapsulate the indexer as I needed to do in example below:

    static class Indexer {
        int i = 0;
    }
    
    public static String getRegex() {
        EnumSet range = EnumSet.allOf(MeasureUnit.class);
        StringBuilder sb = new StringBuilder();
        Indexer indexer = new Indexer();
        range.stream().forEach(
                measureUnit -> {
                    sb.append(measureUnit.acronym);
                    if (indexer.i < range.size() - 1)
                        sb.append("|");
    
                    indexer.i++;
                }
        );
        return sb.toString();
    }
    

提交回复
热议问题