title: Guava Lazy Collection using Supplier interface
body: <p>I would like some kind of generic method to allow me to lazy load a collections contents based on use of the java.util.Collection.get( int ) method. I found the Supplier interface in Guava and this looks like a great way of doing the lazy loading, but how to make the loading invisible in java collections is something I am struggling with.</p>
  
  <p>Below is a sample lazy loading method that iterates through an iterator. </p>
  
  <pre><code>class MySupplier&lt;T&gt; implements Supplier&lt;T&gt; {
      private T s;
      public MySupplier( T s ) {
          this.s = s;
      }
      public T get() {
          System.out.println( String.format( "Lazy loading '%s'", s ) );
          return s;
      }
  }
  
  public void lazyLoad() {
      List&lt;MySupplier&lt;String&gt;&gt; list = Lists.newArrayList( new MySupplier&lt;String&gt;( "a" ), new MySupplier&lt;String&gt;( "a" ), new MySupplier&lt;String&gt;( "b" ), new MySupplier&lt;String&gt;( "c" ), new MySupplier&lt;String&gt;( "d" ) );
      for ( Iterator&lt;MySupplier&lt;String&gt;&gt; i = list.iterator(); i.hasNext(); ) {
          System.out.println( i.next().get() );
      }
  }
  </code></pre>
  
  <p>I want to avoid having to use the Supplier.get() method if I can help it, but instead have a collections wrapper take care of it for me when Collection.get( int ) is called. I hope to achieve this in a simple method call that I called <code>makeLazy( Collection )</code> below.</p>
  
  <pre><code>public void lazyLoad_desired() {
      List&lt;String&gt; list = makeLazy( 
              Lists.newArrayList( new MySupplier&lt;String&gt;( "a" ), new MySupplier&lt;String&gt;( "a" ), new MySupplier&lt;String&gt;( "b" ), new MySupplier&lt;String&gt;( "c" ), new MySupplier&lt;String&gt;( "d" ) )
          );
      for ( Iterator&lt;String&gt; i = list.iterator(); i.hasNext(); ) {
          String s = i.next();
          System.out.println( s );
      }
  }
  </code></pre>
  
  <p>I realise that I would need to override collections somehow, but my knowledge in this area has some gaps. Could somebody give me some hints and tips on what I need to do to implement the makeLazy( Collection ) method?</p>
  
  <p>Thanks,
  Stuart</p>