Get top 5 data from stack
I have use java stack data structure to maintain data. I have limit my stack to be size 50. What I want to do get latest 5 data from the stack from one call. I thought method sublist(0,5) would do it. But unfortunately method returns last 5 data since that method inherited from java.util.list is there any way to do this. Or is there any other data structure which fulfill my requirment. pls help me. Thanks in advance.
P.s I want to remain lates 5 data in the stack after i retrive.
Stack stack = new Stack();
for(int i=0; i<10;i++){
stack.push(""+i);
}
for(int k= 0 ;k<11;k++){
System.out.println(stack.subL开发者_如何转开发ist(0,5));
}
out put of this will be {0,1,2,3,4}. But I want to get {9,8,7,6,5}
the default stack implemantaion does not have the method you need. you will have to pop() your stack 5 times.
So i suggest extending a Stack implementation or write a utility method that group the 5 pops.
something like:
public static <T> List<T> multiPop( Stack<T> stack, int times)
{
List<T> list = new ArrayList<T>();
for ( int i = 0;i<times;i++)
{
list.add(stack.pop());
}
return list;
}
but will need to think on the behaviour of each pop
if you need a multipeek
public static <T> List<T> multiPeek( Stack<T> stack, int depth )
{
int len = stack.size();
if ( len < depth )
throw new EmptyStackException();
List<T> list = new ArrayList<T>();
for (int i = 0; i < depth; i++)
{
list.add(stack.elementAt(len-i-1));
}
return list;
}
If sublist(0,5)
returns the wrong end of your stack, try changing your indices. Instead of starting from 0, start from stack.size()-6
.
As others pointed out you can pop()
5 times as well. In functional languages the operation you are looking for simply referred to as take 5
. It is easy to implement it yourself, but you'd have to derive your own stack class in Java.
Another important point: When you pop()
5 times, those elements will be removed from the stack. This may or may not be what you intend. However, keep in mind, that sublist
will return you a list that may modify the stack itself, so you can easily run into integrity problems there.
Hence, I suggest you write your own stack class and implement a take(n)
method that performs a sublist
call and copies the results into a fresh list, such that the ultimately returned list cannot affect your original stack.
normally if you have an actual stack, you will have a method pop. A stack isn't exactly a straight forward list. You can pop 5 times, but you need to make sure that there is something there to take off the stack.
精彩评论