Freitag, 17. Februar 2012

Lambdaj Closure in Java

Yesterday we played around with the Lambdaj project. The project provides a fancy way to simulate closure in Java. Here some simple examples based on the lambda4j documentation code.

import static ch.lambdaj.Lambda.*;
import static ch.lambdaj.collection.LambdaCollections.*;
import static org.hamcrest.Matchers.*;
import java.util.List;
import javax.swing.JLabel;
import ch.lambdaj.collection.*;
import ch.lambdaj.function.closure.*;
public class LambdaDemo {
public static void main(String[] args) {
// Simple lambda4j closure demo
JLabel label = new JLabel("Test Label Name");
Closure closure = closure(); {of(label).getText();}
System.out.println(closure.apply());
// Simple lambda4j collection demos
LambdaList<Person> list = with(new Person("Michael Jackson"), new Person("Bob"));
System.out.println(joinFrom(list).getName());
// Select elements from a collection
List<Person> select = select(list, having(on(Person.class).getName(), equalTo("Bob")));
System.out.println(joinFrom(select).getName());
// println each person to system.out
Closure1<Person> personClosure = closure(Person.class); {of(System.out).println(var(Person.class));}
personClosure.each(list);
}
static class Person
{
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
}
view raw LambdaDemo.java hosted with ❤ by GitHub


And here a second example with "delayedClosure", which shows how to read a file line by line with lambda4j.

import static ch.lambdaj.Lambda.*;
import java.io.*;
import ch.lambdaj.function.closure.*;
public class FileReaderDemo {
public static void main(String[] args) {
File file = new File(FileReaderDemo.class.getResource("/demo.txt").getFile());
FileReader reader = new FileReader(file);
reader.eachLine(); {
of(System.out).println(var(String.class));
}
}
public static class FileReader {
private final File file;
public FileReader(File file) {
this.file = file;
}
public void eachLine() {
delayedClosure(new DelayedClosure<Void>() {
@Override
public Void doWithClosure(Closure lineReader) {
BufferedReader reader = null;
try {
InputStream stream = new FileInputStream(file);
reader = new BufferedReader(new InputStreamReader(stream));
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
lineReader.apply(line);
}
} catch (IOException ioe) {
throw new RuntimeException("Error while reading file " + file, ioe);
} finally {
try {
if (reader != null) reader.close();
} catch (IOException ioe) {
throw new RuntimeException("Error while closing file reader", ioe);
}
}
return null;
}
});
}
}
}


More details about lambda4j please have a look at the project website:
http://code.google.com/p/lambdaj/