Skip to content

Instantly share code, notes, and snippets.

@criminy
Created September 14, 2011 18:56
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/1217438 to your computer and use it in GitHub Desktop.
Save criminy/1217438 to your computer and use it in GitHub Desktop.
Figuring out the building of lists from functions and lazy lists with memoization.
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
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;
class Counter {
int count = 0;
}
public class LazyListTest {
@Test
public void test() {
{
final Counter count = new Counter();
List<String> s = Lists.transform(
(List<String>) ImmutableList.of("hello","world", "asd"),
new Function<String, String>() {
@Override
public String apply(String input) {
System.out.println("uppercasing " + input);
count.count++;
return input.toUpperCase();
}
});
s.get(0); //each time this is called, "uppercasing hello" is printed.
s.get(0);
s.get(0);
s.get(0);
String str = s.get(0);
assertEquals(5,count.count); //called five times
assertEquals("HELLO",str);
}
{
final Counter count = new Counter();
List<String> s =
Lists.transform(
ImmutableList.copyOf(
Lists.transform(
(List<String>) ImmutableList.of("hello","world", "asd"),
new Function<String, Supplier<String>>()
{
public Supplier<String> apply(String input) {
return Suppliers.memoize(Suppliers.compose(
new Function<String,String>() {
@Override
public String apply(String input) {
System.out.println("uppercasing " + input);
count.count++;
return input.toUpperCase();
}
},
Suppliers.ofInstance(input)));
}})),
new Function<Supplier<String>, String>() {
public String apply(Supplier<String> supplier) {
return supplier.get();
}
});
s.get(1); //the FIRST time this is called, "uppercasing world" is called.
s.get(1); //every other time is cached.
s.get(1);
s.get(1);
String str = s.get(1);
assertEquals(1,count.count); //called once
assertEquals("WORLD",str);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment