title: How to implement the builder pattern in Java 8?
body: <p>Implement the builder pattern prior to Java 8 has lots of tedious, nearly duplicated code; the builder itself is typically boilerplate code. Some <a href="http://clonedigger.sourceforge.net/" rel="noreferrer">duplicate code detectors</a> consider nearly each method of a pre-Java 8 builder as a copy of every other method.</p>
  <p>Consider the following pre-Java 8 builder pattern:</p>
  <pre class="lang-java prettyprint-override"><code>public class Person {
  
      private String name;
      private int age;
  
      public String getName() {
          return name;
      }
  
      public void setName(String name) {
          this.name = name;
      }
  
      public int getAge() {
          return age;
      }
  
      public void setAge(int age) {
          this.age = age;
      }
  }
  
  public class PersonBuilder {
      
      private static class PersonState {
          public String name;
          public int age;
      }
      
      private PersonState  state = new PersonState();
      
      public PersonBuilder withName(String name) {
          state.name = name;
          return this;
      }
      
      public PersonBuilder withAge(int age) {
          state.age = age;
          return this;
      }
      
      public Person build() {
          Person person = new Person();
          person.setAge(state.age);
          person.setName(state.name);
          state = new PersonState();
          return person;
      }
  }
  </code></pre>
  <p>How can the builder pattern be implemented using Java 8?</p>