Tag Archives: java-8

Lambdas and serialization

With the introduction of intersection cast in Java 8, it is now possible to write: Object o = (SomeType & SomeOtherType) otherObject;

One very interesting use case is Serialization as this allows us to automagically serialize a lambda effortlessly:

    File file = Files.createTempFile("lambda", "ser").toFile();
    try (ObjectOutput oo = new ObjectOutputStream(new FileOutputStream(file))) {
        Runnable r = (Runnable & Serializable) () -> System.out.println("I can be serialized!");

    try (ObjectInput oi = new ObjectInputStream(new FileInputStream(file))) {
        Runnable  r = (Runnable) oi.readObject();
Tagged , , ,

Memory conscious toList collector with Java 8

The following code:

    List source = Arrays.asList(1, 2, 3, 4, 5);
    List result = new ArrayList<> (source.size());
    for (int i : source) result.add(2 * i);

can easily be transformed to use lambdas in Java 8, for example:

    List result = source.stream()
                                 .map(i -> 2 * i)

There is however an important difference: in the first code, the result list has a capacity of 5, whereas in the second code it has a capacity of 10, hence using more memory*.

The Collectors utility class also offers a toCollection method which accepts a Supplier<Collection>. That method allows to use a properly sized collection, for example:

    Supplier s = () -> new ArrayList<>(source.size());
    List result = source.stream()
                                 .map(i -> 2 * i)

The code is now equivalent to the original code without lambdas and the result list has an optimal capacity.

*The capacity of the backing array can easily be checked with:

    Field f = ArrayList.class.getDeclaredField("elementData");
    System.out.println(((Object[]) f.get(result)).length);

Tagged , , ,