Thaadikkaaran
Thaadikkaaran

Reputation: 5226

How to copy items from list to stack without using loop

I do have a Stack and a List. I need to copy all the items from list to stack without using loops i.e for, foreach.. etc.

Is there recommended way of doing it?

Upvotes: 15

Views: 20675

Answers (4)

In java 1.8 Stack has a predefined method call addAll - Item will be push on to the stack

stack.addAll(list);

Upvotes: -1

Ε Г И І И О
Ε Г И І И О

Reputation: 12351

If you want to Pop the items in the same order as they appear in your list, then reverse your list before you create the stack from it.

var myStack = new Stack<MyObjectType>(myList.Reverse());

Upvotes: 5

spender
spender

Reputation: 120480

new Stack<T>(myListOfT)

Alternatively (without loops)

myStack.Push(myList[0]);
myStack.Push(myList[1]);
myStack.Push(myList[2]);
myStack.Push(myList[3]);
...

It's going to get pretty tedious. What's wrong with loops?

Upvotes: 0

Colin Mackay
Colin Mackay

Reputation: 19175

You can create a stack from anything that is IEnumerable

var myStack = new Stack<MyObjectType>(myList);

See MSDN: http://msdn.microsoft.com/en-us/library/76atxd68.aspx

However, the stack constructor will be using a loop internally, you just don't see it.

Upvotes: 36

Related Questions