What Is the Simplest Way to Reverse an Arraylist

What is the Simplest Way to Reverse an ArrayList?

Collections.reverse(aList);

Example (Reference):

ArrayList aList = new ArrayList();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
Collections.reverse(aList);
System.out.println("After Reverse Order, ArrayList Contains : " + aList);

added elements in ArrayList in the reverse order in java

Use the reverse method of the Collections class to reverse the list. Please note that this will affect the list itself.

ArrayList logs = new ArrayList(); //Initialize this list or your
//code won't compile.

for(Logs log : getLogs()){
logs.add(log.getName();
}

Collections.reverse(logs);

If you want a new list, create a new one, add all of the elements to it by using addAll and, finally, reverse that one.

Reverse order of characters in every entry in an ArrayList

Quick and dirty version - changing the Strings inside the original ArrayList:

for(int i = 0; i < aa.size(); i++) {
aa.set(i, new StringBuilder(aa.get(i)).reverse().toString());
}

Quickest and most efficient way to traverse an ArrayList in reverse

Depending on the implementation of the List and ListIterator the following may be (slightly) quicker.

List l;
for (int i = l.size()-1; i >=0; i--) {
System.out.println(l.get(i));
}

This may be faster for an ArrayList but it will almost certainly be slower for a LinkedList.

Your best bet is to just use the iterator.

It is almost certain that whatever work you are doing in the loop will negate any performance gained by not using the iterator.

Most efficient way to reverse a stack and add to an ArrayList

The Iterable<T> implementation order of Stack<T> goes in the order you want anyway, so you can just use

new ArrayList<String>(stack);

Here's a short but complete example:

import java.util.*;

public class Test
{
public static void main(String[] args)
{
Stack<String> stack = new Stack<String>();
stack.push("Bottom");
stack.push("Middle");
stack.push("Top");

List<String> list = new ArrayList<String>(stack);

for (String x : list)
{
System.out.println(x);
}
}
}

This prints out:

Bottom
Middle
Top

(which is the opposite order to what you'd get if you popped them).

EDIT: One other question - do you really need it in an ArrayList<String> anyway? Stack<T> implements List<T>; what special features of ArrayList do you need? (I'm not saying you don't need them, just checking!)

How to reverse ArrayList input?

You can try:

ArrayList<Object> objects= new ArrayList<Object>(objects);
Collections.reverse(objects);

Or you can add them at front:

objects.add(0, yourObject);

android - reverse the order of an array

You can do this in two steps:

ArrayList<Element> tempElements = new ArrayList<Element>(mElements);
Collections.reverse(tempElements);


Related Topics



Leave a reply



Submit