Skip to content

Instantly share code, notes, and snippets.

@jasper-lyons
Created May 7, 2015 14:23
Show Gist options
  • Save jasper-lyons/5c52135124fe1033c100 to your computer and use it in GitHub Desktop.
Save jasper-lyons/5c52135124fe1033c100 to your computer and use it in GitHub Desktop.
Super Simple Java7 Functional Collection Interface
package utils;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
// This can be replaced with any other Function / Function2 interface
import play.libs.F.Function;
import play.libs.F.Function2;
public class Seq<E> extends AbstractList<E> {
private List<E> data;
public Seq() {
this.data = new ArrayList<E>();
}
public Seq(List<E> data) {
this.data = data;
}
public Iterator<E> iterator() {
return data.iterator();
}
public boolean add(E value) {
return this.data.add(value);
}
public boolean addAll(Collection<? extends E> collection) {
return this.data.addAll(collection);
}
public E get(int index) {
return this.data.get(index);
}
public int size() {
return this.data.size();
}
public <R> Seq<R> map(Function<E, R> func) throws Throwable {
Seq<R> results = new Seq<R>();
Iterator<E> data = this.iterator();
while(data.hasNext())
results.add(func.apply(data.next()));
return results;
}
public void forEach(Function<E, Void> func) throws Throwable {
Iterator<E> data = this.iterator();
while(data.hasNext())
func.apply(data.next());
}
public Seq<E> filter(Function<E, Boolean> pred) throws Throwable {
Seq<E> results = new Seq<E>();
Iterator<E> data = this.iterator();
while(data.hasNext()) {
E element = data.next();
if (pred.apply(element)) results.add(element);
}
return results;
}
public E reduce(Function2<E,E,E> reducer) throws Throwable {
Iterator<E> data = this.iterator();
E accum = data.next();
while(data.hasNext())
accum = reducer.apply(accum, data.next());
return accum;
}
public <A> A reduceWith(Function2<A,E,A> reducer, A accum) throws Throwable {
Iterator<E> data = this.iterator();
while(data.hasNext())
accum = reducer.apply(accum, data.next());
return accum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment