FluentIterable as a Collection Converter

170 views
Skip to first unread message

eric.giese

unread,
May 15, 2013, 9:45:53 AM5/15/13
to guava-...@googlegroups.com
Hello everyone,

Recently I've been toying around with FluentIterable:

It's really a great piece of work to see how all of its methods work so perfectly together:
FluentIterable.from(Arrays.asList("a", "b")).toList();

Due to runtime inspection done by the different methods of guava, this will actually result in cloning the internal array and hand it directly over to ImmutableList - nearly the same as directly handing over the Array to ImmutableList.copyOf(Array). Its nearly the same for most of the other toXXX Methods. Even transformations could perform extremely well (see #1413 for a potential optimization).

This brought me to an idea: Couldn't FluentIterable be more or less just used as a generic collection converter to create datastructures?

To test this out, I created a class Sequences which defines these few methods:

static FluentIterable seq(E e1, E e2, E e3, .. etc up to 10, then varargs)
static FluentIterable view(E[] iterable)
static FluentIterable view(Iterable<E> iterable)
static FluentIterable concat(Iterable<? extends E> a, Iterable<? extends E> b)

- seq() is used as an nulltolerant alternative to ImmutableList.of() to obtain a FluentIterable of 1..n elements.
- view() allows it to convert any iterable or seq ad-hoc to whatever is needed. The name could be changed to from() or whatever else seems to sound good.
- concat(): FluentIterable.from(Iterables.concat(a, b));

Using this static import via eclipse static favorites allows for some pretty nice, effective and concise coding:

Need an immutable collection?
ImmutableSet<Type> list = view(iterable,array).toSet()

Need a modifiable instead?
List<Type> list = view(iterable, array).copyInto(new ArrayList<Type>());

Want to iterate over some test values, including null?
for (String test : seq("first", "second", null)){ // do some assertions etc

Want to merge two iterables into a SortedList?
concat(iterable1, iterable2).toSortedList(Ordering.natural())

And so on...

What does it give? It allows it to leverage nearly all iterable functions from java's and guava's collection library in a fluent way without needing to know all pitfalls or special calls - like using Ordering.immutableSortedCopy to get the sortedList. Also, in the case of Sorted Collections, this forces the user to specify the comparator to use.

From a designer's perspective, do you think it is a good idea to introduce a class with these static methods and encourage all programmer's to use them where possible to create immutable the datastructures by a combination of view().toXX() where appropiate?




Reply all
Reply to author
Forward
0 new messages