Skip to content

Instantly share code, notes, and snippets.

@SubOptimal
Created November 30, 2018 09:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SubOptimal/71403236a52f7bdf2845ececb8cb20df to your computer and use it in GitHub Desktop.
Save SubOptimal/71403236a52f7bdf2845ececb8cb20df to your computer and use it in GitHub Desktop.
tuples in Java streams
// as long answer to https://twitter.com/pivovarit/status/1067883547669815296
import java.lang.reflect.Field;
import java.util.Arrays;
class Tuples {
public static void main(String... args) throws NoSuchFieldException, IllegalAccessException {
new Tuples().exec();
}
// - if executed as instance method the instances of the anonymous class keep a reference to the enclosing Tuples
// instance, if the objects are exposed outside the stream there is a risk for a memory leak
//
// - if executed in a static context the instances of the anonymous class don't keep a reference to the enclosing
// Tuples instance
void exec() {
Arrays.asList("1", "22").stream()
.map(v -> new Object() {
String name = v;
int length = v.length();
})
.peek(Tuples::showRef)
.filter(tuple -> tuple.length % 2 == 0)
.forEach(tuple -> System.out.println(tuple.name));
}
static void showRef(Object o) {
try {
Field field = o.getClass().getDeclaredField("this$0");
if (field.canAccess(o)) {
field.setAccessible(true);
}
System.out.println("enclosing " + field.get(o).getClass());
} catch (Exception e) {
System.out.println("oops... " + e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment