title: Java: The elegant way to add a line number to a file with lambda
body: <p>I get used to using lambda to parse file line by line(much neater than <code>bufferedReader.readLine()</code>) for a long time. But today I faced a problem: add a line number to each line. </p>
  
  <p>It need a counter, but the variable in lambda should be effectively final.  Finally, I hacked it with an int array.</p>
  
  <p>Code:</p>
  
  <pre><code>public static void main(String[] args) {
      int[] counter = new int[1];
      counter[0] = 0;
      try (Stream&lt;String&gt; lines = Files.lines(Paths.get("/tmp/timeline.txt"), Charset.defaultCharset())) {
          lines.limit(10).forEachOrdered(line -&gt; {
              line = line.trim();
              counter[0] ++;
              System.out.println("Line " + counter[0] + ": " + line);
          });
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>Line 1: p 5714026 wEkQ
  Line 2: v 8235889
  Line 3: v 6534726
  ...
  </code></pre>
  
  <p>My question is, how to avoid my hack and solve that problem elegantly?</p>