3

i'm using java.util.Stack but i'm missing a multipop

stack.pop(10);

which should give me a list of 10 (or less is the stack does not contain enough) items from the stack (and remove them from the stack). Is there any standard class in java? or have i to implement it by myselfe?

Zoe
  • 27,060
  • 21
  • 118
  • 148
wutzebaer
  • 14,365
  • 19
  • 99
  • 170

4 Answers4

4

There is not a multipop method. You could extend Stack to add your own functionality.

public class ImprovedStack<E> extends Stack<E> {

    public synchronized E[] pop(int count) {
        E[] objs = new E[count];
        for (int i = 0; i < count; i++) {
            objs[i] = pop();
        }
        return objs;
    }
}

With this implementation, an EmptyStackException will be thrown if the stack has fewer objects than count, but you can modify it to your needs.

FThompson
  • 28,352
  • 13
  • 60
  • 93
3

In Eclipse Collections there is an alternative Stack implementation called ArrayStack that provides exactly this type of behavior.

MutableStack<String> stack =
    Stacks.mutable.with("j", "i", "h", "g", "f", "e", "d", "c", "b", "a");

ListIterable<String> result = stack.pop(2);
Assert.assertEquals(Lists.mutable.with("a", "b"), result);

ArrayList<String> arrayList = stack.pop(4, new ArrayList<>());
Assert.assertEquals(Arrays.asList("c", "d", "e", "f"), arrayList);

Assert.assertEquals(Stacks.mutable.withReversed("g", "h", "i", "j"), stack);

MutableBag<String> bag = stack.pop(4, Bags.mutable.empty());
Assert.assertEquals(Bags.mutable.with("g", "h", "i", "j"), bag);

Assert.assertTrue(stack.isEmpty());

There is also support for a multi-peek, via peek(int).

Note: I am a committer for Eclipse Collections.

Donald Raab
  • 6,458
  • 2
  • 36
  • 44
2

Don't think there is any standard impl for this in Java; have a look at this related question. (i think the answers here are quite concise)

Community
  • 1
  • 1
acostache
  • 2,177
  • 7
  • 23
  • 48
1

You could use a NavigableSet that would keep the data in the order you prefer ( use a custom comparator for this) and allows you to query a headset, subset or a tailset.

Scorpion
  • 3,938
  • 24
  • 37