How to reverse List in Java Collection Framework?

UPDATED: 16 December 2014
Collections Framework Reverse Java


List allows to add String and Custom bean elements in it. To reverse the given list we can use Collections.reverse(List<?> list).

Source Code
/**
 * @author javaQuery
 */
public class User{

    private String Firstname;
    private String Lastname;

    public String getFirstname() {
        return Firstname;
    }

    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }

    public String getLastname() {
        return Lastname;
    }

    public void setLastname(String Lastname) {
        this.Lastname = Lastname;
    }
}
import com.javaquery.beans.User;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author javaQuery
 */
public class ReverseListExample {

    public static void main(String[] args) {
        /* Create list of String */
        List<String> listString = new ArrayList<String>();
        /* Add elements in listString */
        listString.add("a");
        listString.add("b");
        listString.add("c");

        System.out.println("Initial List");
        System.out.println(listString);
        System.out.println("------------------------");

        Collections.reverse(listString);
        System.out.println("Reverse List");
        System.out.println(listString);
        System.out.println("------------------------");

        /* Create object of User */
        User user1 = new User();
        /* Set Firstname of User */
        user1.setFirstname("Vicky");
        /* Set Lastname of User */
        user1.setLastname("Thakor");

        User user2 = new User();
        user2.setFirstname("Chirag");
        user2.setLastname("Thakor");

        User user3 = new User();
        user3.setFirstname("Heer");
        user3.setLastname("Thakor");
        
        /* Add Users in List<User> */
        List<User> listUser = new ArrayList<User>();
        /* Add elements in listUser */
        listUser.add(user1);
        listUser.add(user2);
        listUser.add(user3);

        System.out.println("Initial List");
        System.out.println("------------------------");
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }
        System.out.println("------------------------");
        System.out.println("Reverse List");
        System.out.println("------------------------");
        Collections.reverse(listUser);
        for (User user : listUser) {
            System.out.println(user.getFirstname() + " " + user.getLastname());
        }        
    }
}

Output
[a, b, c]
------------------------
Reverse List
[c, b, a]
------------------------
Initial List
------------------------
Vicky Thakor
Chirag Thakor
Heer Thakor
------------------------
Reverse List
------------------------
Heer Thakor
Chirag Thakor
Vicky Thakor

0 comments :