Skip to content

Instantly share code, notes, and snippets.

@criminy
Created September 12, 2011 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save criminy/1212323 to your computer and use it in GitHub Desktop.
Save criminy/1212323 to your computer and use it in GitHub Desktop.
Lazy List Utilities useful for lazy-loading of DAO collections.
RepositoryInstance repositoryInstance; //some Repository which has findById.
List<T> lazyList = LazyListUtil.idListToLazyList(jdbcTemplate.queryForList("select foreign_key from join_table where primary_key = ?",new Object[]{id},String.class),repositoryInstance));
// The only query run so far "select foreign key from join_table where primary_key = ?" . the others aren't run until we use lazyList, which would be inside RepositoryInstance.
import java.util.List;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public class LazyListUtil {
public static <T> Function<Supplier<T>, T> supplyFunction() {
return new Function<Supplier<T>, T>() {
public T apply(Supplier<T> supplier) {
return supplier.get();
}
};
}
public static <T> List<T> idListToLazyList(List<String> ids, final Repository<T> repo) {
return Lists.transform((List<Supplier<T>>)
ImmutableList.copyOf(
Lists.transform(
ids,
new Function<String, Supplier<T>>() {
public Supplier<T> apply(String key) {
return Suppliers.memoize(Suppliers.compose(
new Function<String,T>() {
@Override
public T apply(String arg0) {
return repo.findById(arg0);
}
},
Suppliers.ofInstance(key)));
}
})),
LazyListUtil.<T>supplyFunction());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment