728x90 AdSpace

Sunday, 31 May 2015

How to reverse the Collection (List)

Following example shows how to reverse the collection (List) using Collections.reverse(arg0); method in Java.

void java.util.Collections.reverse(List<?> list)
reverse

public static void reverse(List<?> list)
Reverses the order of the elements in the specified list.This method runs in linear time.
Parameters:
    list - the list whose elements are to be reversed.
Throws:
    UnsupportedOperationException - if the specified list or its list-iterator does not support the set operation.

Sample Program
ReverseCollection.java
package com.javatutorialcorner.collection;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ReverseCollection {

	public static void main(String[] args) {
		String[] nameArray = new String[] { "Spring", "Struts", "Hibernate",
				"Webservice", "SOAP Webservice", "RESTful Webservice" };
		List<String> nameList = Arrays.asList(nameArray);

		System.out.println("*********** Before Reverse ************");
		for (String name : nameList) {
			System.out.println(name);
		}
		Collections.reverse(nameList);
		System.out.println("*********** After Reverse ************");

		for (String name : nameList) {
			System.out.println(name);
		}

	}

}

Result
The above code will produce the following output.
*********** Before Reverse ************
Spring
Struts
Hibernate
Webservice
SOAP Webservice
RESTful Webservice
*********** After Reverse ************
RESTful Webservice
SOAP Webservice
Webservice
Hibernate
Struts
Spring
Annamalai Thangaraj

Annamalai is working as Technical Lead in Leading Telecom company with 5+ years experience in Identity and Access Management , Telecom and Networks, BigData, Java, Spring, Struts, Hibernate, AngularJS, and Enterprise Web Application Development.

Website: Java Tutorials Corner

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to reverse the Collection (List) Rating: 5 Reviewed By: Annamalai Thangaraj