Try this:
// Substitute appropriate type.
ArrayList<...> a = new ArrayList<...>();
// Add elements to list.
// Generate an iterator. Start just after the last element.
ListIterator li = a.listIterator(a.size());
// Iterate in reverse.
while(li.hasPrevious()) {
System.out.println(li.previous());
}
Answer from John Feminella on Stack Overflowcollections - Iterating through a list in reverse order in java - Stack Overflow
[Java] Need help reversing integers of a List into a separate ArrayList.
[JAVA] Is there a way to make this reverse method more efficient? Possibly requiring only one loop?
Can one do a for each loop in java in reverse order? - Stack Overflow
Videos
Try this:
// Substitute appropriate type.
ArrayList<...> a = new ArrayList<...>();
// Add elements to list.
// Generate an iterator. Start just after the last element.
ListIterator li = a.listIterator(a.size());
// Iterate in reverse.
while(li.hasPrevious()) {
System.out.println(li.previous());
}
Guava offers Lists#reverse(List) and ImmutableList#reverse(). As in most cases for Guava, the former delegates to the latter if the argument is an ImmutableList, so you can use the former in all cases. These do not create new copies of the list but just "reversed views" of it.
Example
List reversed = ImmutableList.copyOf(myList).reverse();
This is a review question for my upcoming intro to programming exam and I need some help fixing my code. The question explicitly states to write a method that takes a List of integers and returns a new ArrayList in reverse order. It also says that we can assume we have methods prepend and append which add a new element to the beginning/end.
Here is my current code which gives me a NullPointerException
public static ArrayList<Integer> reverse(List<Integer> list){
ArrayList<Integer> list2 = new ArrayList<Integer>();
list.add(5);
list.add(10);
list.add(15);
list.add(20);
System.out.println(list);
for(int i = 0, j = list.size()-1; i < j; i++){
list2.add(i, list.remove(j));
}
return list2;
}
public static void main(String[] args){
reverse(null);
}Any help would be greatly appreciated. Thank you.
Edit: I am getting closer, 2 of the 4 objects are being reversed and displayed. More information is in the comments below.
Edit2: Thank you so much for all the help today guys, I understand this concept a lot better after reading through everyone's comments!
//code inside a reverse method that has the list object
//passed as a parameter from main method
int size = list.size();
//create temporary list object to hold contents of original list in reverse
MyListReferenceBased temp = new MyListReferenceBased();
for (int i = 0; i < size; i++)
{
//list add method requires which index your adding to, and object
//get method just gets the object at the specified index in list
temp.add(i, list.get((size-i)-1));
//remove method just removes object at specified index
list.remove((size-i)-1);
}
//now that original list is empty, put the contents back in
for (int i = 0; i<size; i++)
{
list.add(i, temp.get(i));
}
temp.removeAll();
//end result: original list is now reversed and temporary array is all empty
System.out.println("List has been Reversed.");
//is there a way to get rid of the 2nd loop?? Not possible to just assign?So this code is in a reverse method inside the main class for reversing a linked list. Well reversing a list in general, since the user of the main class isn't suppose to interact with the linked list directly but just has access to the linked list methods (Didn't do reverse inside linked list class on purpose). Rather in the main/driver class, I'm reversing the list by first creating a second/temporary linked list, adding over each of the elements from the original list (in reverse) into the new list. And then since I need the contents to be in the original list and only need the temporary list during the duration of this method, I copy over the elements back into the old list.
The list object is instantiated as local in the main method of this main class and then calls the reverse method, passing the list object as a parameter. Instead of having the second loop, isn't there a way to just assign the temporary list object to the original list? I was able to do this when I the underlying implementation of the list was using arrays, but not sure how to it with linked lists.
Or any other efficient work around? Remember this is specifically for reversing a linked list without directly being inside the linked list class.
One approach would be to reverse the whole list, but this would have O(n) performance with respect to its size. Note that the commonly-used Collections.reverse method actually reverses the original list in place, which may be an undesirable side-effect.
As a more efficient solution, you could write a decorator that presents a reversed view of a List as an Iterable. The iterator returned by your decorator would use the ListIterator of the decorated list to walk over the elements in reverse order.
For example:
Copypublic class Reversed<T> implements Iterable<T> {
private final List<T> original;
public Reversed(List<T> original) {
this.original = original;
}
public Iterator<T> iterator() {
final ListIterator<T> i = original.listIterator(original.size());
return new Iterator<T>() {
public boolean hasNext() { return i.hasPrevious(); }
public T next() { return i.previous(); }
public void remove() { i.remove(); }
};
}
public static <T> Reversed<T> reversed(List<T> original) {
return new Reversed<T>(original);
}
}
And you would use it like:
Copyimport static Reversed.reversed;
...
List<String> someStrings = getSomeStrings();
for (String s : reversed(someStrings)) {
doSomethingWith(s);
}
Update for Java 21
As per this answer, Java 21 includes an efficient List.reversed() method which does exactly what is requested.
For a list, you could use the Google Guava Library:
Copyfor (String item : Lists.reverse(stringList))
{
// ...
}
Note that Lists.reverse doesn't reverse the whole collection, or do anything like it - it just allows iteration and random access, in the reverse order. This is more efficient than reversing the collection first.
To reverse an arbitrary iterable, you'd have to read it all and then "replay" it backwards.
(If you're not already using it, I'd thoroughly recommend you have a look at the Guava. It's great stuff.)