Created
November 30, 2018 09:11
-
-
Save SubOptimal/71403236a52f7bdf2845ececb8cb20df to your computer and use it in GitHub Desktop.
tuples in Java streams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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