Micha Kops avatar Micha Kops committed a33c25f

Transformer and closure examples for commons-collections added.

Comments (0)

Files changed (1)

src/main/java/com/hascode/tutorial/CommonsCollectionExample.java

 package com.hascode.tutorial;
 
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.Date;
 import java.util.Iterator;
 import java.util.List;
 
+import org.apache.commons.collections.Closure;
+import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.Predicate;
+import org.apache.commons.collections.Transformer;
 import org.apache.commons.collections.iterators.FilterIterator;
 
 public class CommonsCollectionExample {
 		// output:
 		// Some book
 		// Another book
+
+		Closure closure = new Closure() {
+			public void execute(final Object obj) {
+				Book book = (Book) obj;
+				System.out.println("the book's title is: " + book.getTitle());
+			}
+		};
+		CollectionUtils.forAllDo(books, closure);
+		// the book's title is: Some book
+		// the book's title is: Another book
+		// the book's title is: I luv codin
+
+		Transformer transformer = new Transformer() {
+			public Object transform(final Object obj) {
+				Book book = (Book) obj;
+				return new Book("X " + book.getTitle(), book.getPublished());
+			}
+		};
+		Collection<Book> transformedBooks = CollectionUtils.collect(books,
+				transformer);
+		CollectionUtils.forAllDo(transformedBooks, closure);
+		// the book's title is: X Some book
+		// the book's title is: X Another book
+		// the book's title is: X I luv codin
 	}
 }
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.