guavas
As your [Guava] trick shows, most of the operations in the Guava collection are lazy - they are applied only once. For instance:
List<String> strings = Lists.newArrayList("1", "2", "3"); List<Integer> integers = Lists.transform(strings, new Function<String, Integer>() { @Override public Integer apply(String input) { System.out.println(input); return Integer.valueOf(input); } });
This code seems to convert a List<String> to a List<Integer> , and also writes the lines to the output. But if you actually run it, it does nothing. Add another code:
for (Integer i : integers) { // nothing to do }
Now he is recording the entries!
This is because the Lists.transform() method does not actually perform the conversion, but returns a specially created class that only calculates values when they are needed.
Bonus proof that all this works great: if we removed the empty loop and replaced it, for example. just integers.get(1); , in fact, it will only output the number 2 .
If you want to combine several methods together, there is always a FluentIterable . This allows you to code in Java 8 Stream style.
Goldman Sachs Collections
Although Guava usually does the right thing by default and works with JDK classes, sometimes you need something more complex. Where the Goldman Sachs collections are going. GS collections give you much more flexibility and power thanks to having a complete set of collections, taking into account everything you could dream of. Laziness is not the default, but can be easily achieved:
FastList<String> strings = FastList.newListWith("1", "2", "3"); LazyIterable<Integer> integers = strings.asLazy().collect(new Function<String, Integer>() { @Override public Integer valueOf(String string) { System.out.println(string); return Integer.valueOf(string); } });
Again, does nothing. But:
for (Integer i : integers) { // nothing to do }
unexpectedly displays everything.