Monday, June 27, 2016

Java Collections class methods example



package com.corejava.collection;
import java.util.*;
class CollectionsDemo
{
public static void main(String[] args)
{
  List list = new ArrayList();
  list.add(20);
  list.add(2);
  list.add(34);
  list.add(1);
  list.add(5);
  list.add(45);

  //Using Collections class method, we can do many operation, lets do with one by one

  //As we know , list can hold the insertion order, if you want to reverse the insertion order,
  //Use the Collections.reverse(list) method to reverse the elements from list

  Collections.reverse(list);

  //If you want to sort the elements accoridng the asscending order then we can use

  Collections.sort(list);
  //If you want to find the Maximum or Minimum elements from the list then

  Collections.max(list);
  Collections.min(list);

  //If you want to synchronize the list, which is not a synchronized then

  Collections.synchronizedCollection(list);
  // Or
  Collections.synchronizedList(list);

  Collections.shuffle(list);
  System.out.println(" List is :"+list.toString());

  HashMap map = new HashMap();
  map.put("one", 1);
  map.put("two", 2);
  map.put("three", 3);
  //for synchronizing the map using the collections class
  Collections.synchronizedMap(map);
 
 Set  set = new HashSet();
 set.add(10);
 set.add(2);
 set.add(23);
 set.add(44);
 set.add(1);
 Collections.max(set);
 Collections.min(set);
 Collections.synchronizedSet(set);//or
 Collections.synchronizedCollection(set);  
     }
}

No comments:

Post a Comment