Use the .clone() method on your List. It will return a shallow copy, meaning that it will contain pointers to the same objects, so you won't have to copy the list. Then just use Collections.
Ergo,
Collections.reverse(list.clone());
If you are using a List and don't have access to clone() you can use subList():
List<?> shallowCopy = list.subList(0, list.size());
Collections.reverse(shallowCopy);
Answer from jcalvert on Stack Overflowreversing a linkedList explanation- Java
[Java] Need help reversing integers of a List into a separate ArrayList.
java - What is the Simplest Way to Reverse an ArrayList? - Stack Overflow
[JAVA] Is there a way to make this reverse method more efficient? Possibly requiring only one loop?
Videos
Use the .clone() method on your List. It will return a shallow copy, meaning that it will contain pointers to the same objects, so you won't have to copy the list. Then just use Collections.
Ergo,
Collections.reverse(list.clone());
If you are using a List and don't have access to clone() you can use subList():
List<?> shallowCopy = list.subList(0, list.size());
Collections.reverse(shallowCopy);
Guava provides this: Lists.reverse(List)
List<String> letters = ImmutableList.of("a", "b", "c");
List<String> reverseView = Lists.reverse(letters);
System.out.println(reverseView); // [c, b, a]
Unlike Collections.reverse, this is purely a view... it doesn't alter the ordering of elements in the original list. Additionally, with an original list that is modifiable, changes to both the original list and the view are reflected in the other.
Hi all,
I am struggling to understand how you reverse a linkedList.
I have done some googling and found this:
ListNode reverseList(ListNode head) {
ListNode previous = null;
ListNode current = head;
while (current != null) {
ListNode nextElement = current.getNext();
current.setNext(previous);//line a
previous = current; //line b
current = nextElement;
}
return previous;
}
I don't understand purpose of lines a and b. Could you explain?
How is this reversing the list? Honestly, so confused that I cann't even formulate the correct question.
let me know if u can help. Thanks in advance.
I am familiar with Java so try to keep that in mind with the explanations please.
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!
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);
The trick here is defining "reverse". One can modify the list in place, create a copy in reverse order, or create a view in reversed order.
The simplest way, intuitively speaking, is Collections.reverse:
Collections.reverse(myList);
This method modifies the list in place. That is, Collections.reverse takes the list and overwrites its elements, leaving no unreversed copy behind. This is suitable for some use cases, but not for others; furthermore, it assumes the list is modifiable. If this is acceptable, we're good.
If not, one could create a copy in reverse order:
static <T> List<T> reverse(final List<T> list) {
final List<T> result = new ArrayList<>(list);
Collections.reverse(result);
return result;
}
This approach works, but requires iterating over the list twice. The copy constructor (new ArrayList<>(list)) iterates over the list, and so does Collections.reverse. We can rewrite this method to iterate only once, if we're so inclined:
static <T> List<T> reverse(final List<T> list) {
final int size = list.size();
final int last = size - 1;
// create a new list, with exactly enough initial capacity to hold the (reversed) list
final List<T> result = new ArrayList<>(size);
// iterate through the list in reverse order and append to the result
for (int i = last; i >= 0; --i) {
final T element = list.get(i);
result.add(element);
}
// result now holds a reversed copy of the original list
return result;
}
This is more efficient, but also more verbose.
Alternatively, we can rewrite the above to use Java 8's stream API, which some people find more concise and legible than the above:
static <T> List<T> reverse(final List<T> list) {
final int last = list.size() - 1;
return IntStream.rangeClosed(0, last) // a stream of all valid indexes into the list
.map(i -> (last - i)) // reverse order
.mapToObj(list::get) // map each index to a list element
.collect(Collectors.toList()); // wrap them up in a list
}
nb. that Collectors.toList() makes very few guarantees about the result list. If you want to ensure the result comes back as an ArrayList, use Collectors.toCollection(ArrayList::new) instead.
The third option is to create a view in reversed order. This is a more complicated solution, and worthy of further reading/its own question. Guava's Lists#reverse method is a viable starting point.
Choosing a "simplest" implementation is left as an exercise for the reader.