Tag Archives: collector

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)
                                 .collect(toList());

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)
                                 .collect(toCollection(s));

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");
    f.setAccessible(true);
    System.out.println(((Object[]) f.get(result)).length);


Tagged , , ,