Skip to content

Instantly share code, notes, and snippets.

@hertzsprung
hertzsprung / Dazzle8.java
Created June 20, 2012 21:08
Java 8 ActionListener
button.addActionListener(e -> { ui.dazzle(e.getModifiers()); });
@hertzsprung
hertzsprung / PredicateFilter.java
Created June 21, 2012 20:03
Filtering a collection with a predicate
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");
List<String> filteredNames = names
.filter(e -> e.length() >= 4)
.into(new ArrayList<String>());
for (String name : filteredNames) {
System.out.println(name);
}
@hertzsprung
hertzsprung / PredicateFilterAndForEachBlock.java
Created June 21, 2012 20:11
Internal iteration with forEach()
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");
names
.filter(e -> e.length() >= 4)
.forEach(e -> { System.out.println(e); });
@hertzsprung
hertzsprung / FunctionalCollectionComputation.java
Created June 21, 2012 20:42
Functional computation on a collection
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "Dave");
names
.mapped(e -> { return e.length(); })
.asIterable() // returns an Iterable of BiValue elements
// an element's key is the person's name, its value is the string length
.filter(e -> e.getValue() >= 4)
.sorted((a, b) -> a.getValue() - b.getValue())
.forEach(e -> { System.out.println(e.getKey() + '\t' + e.getValue()); });
@hertzsprung
hertzsprung / ConstructorReference.java
Created June 22, 2012 20:46
Factory pattern with constructor reference
Factory<Biscuit> biscuitFactory = Biscuit::new;
Biscuit biscuit = biscuitFactory.make();
@hertzsprung
hertzsprung / ArbitraryObjectMethodReference.java
Created June 22, 2012 21:54
Method reference for an arbitrary object
interface Accessor<BEAN, PROPERTY> {
PROPERTY access(BEAN bean);
}
public static void main(String[] args) {
Address address = new Address("29 Acacia Road", "Tunbridge Wells");
Accessor<Address, String> accessor = Address::getCity;
System.out.println(accessor.access(address));
}
@hertzsprung
hertzsprung / StaticMethodReference.java
Created June 22, 2012 22:01
Static method reference
executorService.submit(MethodReference::sayHello);
private static void sayHello() {
System.out.println("hello");
}
@hertzsprung
hertzsprung / InstanceMethodReference.java
Created June 22, 2012 22:07
Instance method reference
Arrays.asList("Alice", "Bob", "Charlie", "Dave").forEach(System.out::println);
@hertzsprung
hertzsprung / Queue.java
Created June 22, 2012 22:49
Default interface method
interface Queue {
Message read();
void delete(Message message);
void deleteAll() default {
Message message;
while ((message = read()) != null) {
delete(message);
}
}
}
@hertzsprung
hertzsprung / BatchQueue.java
Created June 22, 2012 22:50
Default method override
interface BatchQueue extends Queue {
void setBatchSize(int batchSize);
void deleteAll() default {
setBatchSize(100);
Queue.super.deleteAll();
}
}