Search code examples
javalambdajava-streamstructured-bindings

Java 8+ Unpacking Primitives From Singleton Objects Using Lambda or Stream? Structured Binding in Java?


Effectively I need to take a subset of data out of a function return, but I don't actually need the returned object. So, is there a way to simply take what I need with a Stream or a Lambda-like syntax? And yes, I understand you CAN use stream().map() to put values into an array, and then decompose the array into named variables, but that's even more verbose for functionally equivalent code.

In C++, this would be called Structured Binding, but I seem to be missing the Java term for it when I search.

Procedural code I seem to be forced to write:

HandMadeTuple<Integer, Integer, ...> result = methodICurrentlyCall(input);
int thing1 = result.getFirst();
int thing2 = result.getSecond();
...
//thingX's get used for various purposes. Result is never used again.

Declarative code I'd like to be able to write:

int thing1, thing2;
(methodICurrentlyCall(input)) -> (MyType mt) { thing1 = mt.getFirst(); thing2 = mt.getSecond(); };

Or

int thing1, thing2;
Stream.of(methodICurrentlyCall(input)).forEach((mt) -> { thing1 = mt.getFirst(); thing2 = mt.getSecond();} 

Solution

  • There's a really awkward hack: arrays.

    final int[] thing1 = {0}, thing2 = {0};
    Stream.of(methodICurrentlyCall(input))
      .forEach(mt -> {
        thing1[0] = mt.getFirst();
        thing2[0] = mt.getSecond();
      });
    

    The array reference is final, therefore you can use it in lambdas.

    I don't recommend this! It is neither shorter nor easier to understand

    (Another option is using AtomicReference<T> or AtomicInteger/AtomicLong instead of the array, but there's a minimal overhead for guaranteeing atomic updates)


    If you are looking for pattern matching or destructuring support for Java, this could be implemented in future versions of Java, see this related question on SO: Java object destructuring (even more details at https://cr.openjdk.java.net/~briangoetz/amber/serialization.html)