How to integrate a count variable in a Java stream expression

43 Views Asked by At

The following approach does not compile (variable i should be final):

  void appendLines(StringBuilder sb, String str) {
    str.lines().forEach(s -> {
      int i = 0; 
      sb.append("\n  [").append(i++).append("] ").append(s).append("\n");
    });
  }

An ugly workaround:

  void appendLines(StringBuilder sb, String str) {
    class Counter {
      int i = 0;
      int inc() {
        return i++; 
      } 
    };
    Counter i = new Counter();
    str.lines().forEach(s -> sb.append("\n  [").append(i.inc()).append("] ").append(s));
  }

I think, there should be a more elegant solution, maybe with

static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)

, but unfortunately I don't know how to use it.

0

There are 0 best solutions below