Search code examples
prependeclipse-collections

Eclipse Collections, prepend immutable list


How to prepend (ideally O(1)) to an immutable List (of Eclipse Collections)


Solution

  • There is no ImmutableList that you can prepend to with o(1) behavior in Eclipse Collections today, but you might be able to use an ImmutableStack for similar behavior depending on what you are trying to do.

    ImmutableStack<Integer> stack = Stacks.immutable.empty();
    stack = stack.push(1);
    stack = stack.push(2);
    stack = stack.push(3);
    Assert.assertEquals(Stacks.immutable.with(1, 2, 3), stack);
    
    // Eclipse Collections 10.x
    ImmutableList<Integer> list1 = stack.toList().toImmutable();
    Assert.assertEquals(Lists.immutable.with(3, 2, 1), list1);
    
    // Eclipse Collections 11.x
    ImmutableList<Integer> list2 = stack.toImmutableList();
    Assert.assertEquals(Lists.immutable.with(3, 2, 1), list2);