Core Java Tutorial

 
 

Collections in Java

         Class Collections
                java.lang.Object
                      java.util.Collections

Collections, which are very powerfull in java,collections in java contains classes and interfaces(List&Set) which help to sort and manipulate the data.Collection is nothing but a single unit of objects.In this chapter you are going to know about different classes and interfaces which are presents in Collections along with some of the methods.One of the important about collections is data stored on collections are encapsulated and accessble to only pre-deifned Methods.

CollectionsMain

Iteratorts

Each Collections provides iterator() method , These are mainly used to get each element at a time in collections.By using iterator object you can access each element in Collections.

There are mainly three methods are present in Iterator

  1. boolean hasNext() -- It return true if there is one more element or it returns false if we don't have any element after this in a loop.
  2. Objcet next() -- It return an element and after that it will go to next cursor position.It will throw NoSuchElementException if the elements are other than text.
  3. void remove() --It removes the next element.
  4.      Ex:
              // printing first 2 numbers
              import java.util.ArrayList;
              import java.util.Iterator;
              import java.util.List;
    
            public class ArrayListDemo {
    	public static void main(String[] args) {
    		
    		List li= new ArrayList();
    		li.add(1);
    		li.add(2);
    		
    		//System.out.println("size of array is: "+li.size());
    		//System.out.println("first five numbers: "+li.subList(0,5));
    		Iterator iterator = li.iterator();
    		while(iterator.hasNext()){
    			Object values=iterator.next();
    			System.out.println("values in List are: "+values);
    			}
    		}
    }
    Output:
    values in List are: 1
    values in List are: 2
    

    List

    java.util.List inteface extends collection interface and also List interface have some methods to manage ordered collection of objects.There are mainly two classes which implements List interface, they are ArrayList(Better performance than others) and LinkedList(Less Performance than ArrayList).In this tutorial we will talk about ArrayList more.Keypoints about List are


      List
    1. Guarantees insertion order
    2. Provides methods to access random numbers
    3. Allow duplicates

      Some of methods() in List interface
    1. add(int index, E element) - Insert an element at a specific location (without an index argument, new elements are appended to the end)
    2. get(int index) - Return an element at the specified location
    3. remove(int index) - Remove an element at the specified location
    4. set(int index, E element) - Replace the element at the specified location
    5. subList(int fromIndex, int toIndex) - Returns as a List a modifiable view of the specified portion of the list (that is, changes to the view actually affect the underlying list)
    Example 1: ArrayListDemo.java
    package com.collections.first;
    // adding element at specified index
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    public class ArrayListDemo {
    	public static void main(String[] args) {
    		List li= new ArrayList();
    		li.add("iam");
    		li.add(1, "Hey"); // here we are inserting Hey value at index 1
    		li.add("Ram");
    		li.add("reddy");
    		li.add("kallam");
    		li.add("thank you");
    		li.add("java");
    		System.out.println("elements in colection are:"+li);
    		Iterator it = li.iterator();
    		while(it.hasNext()){
    			Object values=it.next();
    			System.out.println(values);
    		}
    	}
    	
    
    }
    
    Output:
    elements in colection are:[iam, Hey, venkat, reddy, kallam, thank you, java]
    iam
    Hey
    Ram
    reddy
    kallam
    thank you
    java
    
    Example 2:LinkedListDemo.java
    package com.collections.first;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.List;
    
    // printing first 2 numbers
    
    
    public class LinkedListDemo {
    	public static void main(String[] args) {
    		
    		List li= new LinkedList();
    		li.add(1);
    		li.add(2);
    		li.add(4);
    		li.add(5);
    		li.add(6);
    		
    		
    		//System.out.println("size of array is: "+li.size());
    		System.out.println("first five numbers: "+li.subList(0,5));
    		Iterator iterator = li.iterator();
    		while(iterator.hasNext()){
    			
    			Object values=iterator.next();
    			
    			System.out.println("values in List are: "+values);
    			}
    		}
    }
    Output:
    first five numbers: [1, 2, 4, 5, 6]
    values in List are: 1
    values in List are: 2
    values in List are: 4
    values in List are: 5
    values in List are: 6
    
    
    

    Set

    java.util.set inteface extends collection interface and also Set interface have some methods to manage ordered collection of objects that contain no duplicate elements.There are mainly three diiferent classes which implements set interface, They are LinkedHashSet,TreeSet & HashSet and one interface SortedSet.Keypoints about Set interface are


      Set
    1. Guarantees uniqueness
    2. Not in insertion order
    3. Don't Allow duplicates
    4. Set can contain one null value
    5. If you want insertion order use LinkedHashSet
    6. If you want to sort data use TreeSet
    Example:SetDemo.java
    package com.collections.first;
    
    import java.util.HashSet;
    import java.util.LinkedHashSet;
    import java.util.Set;
    import java.util.TreeSet;
    
    public class SetDemo {
    	public static void main(String[] args) {
    		Set hashSet = new HashSet();
    		Set linkedHashSet = new LinkedHashSet();
    		Set treeSet = new TreeSet();
    		//HashSet
    		hashSet.add("Hi");
    		hashSet.add("1Hi");
    		hashSet.add("2Hi");
    		//LinkedHashSet
    		linkedHashSet.add("3Hi");
    		linkedHashSet.add("2Hi");
    		linkedHashSet.add("Hi");
    		linkedHashSet.add("Hi"); // this will not print in output
    		//treeSet
    		treeSet.add("1Hi");
    		treeSet.add("3Hi2");
    		treeSet.add("2Hi3");
    		
    		System.out.println("HashSet values are :"+hashSet);
    		System.out.println("linkedHashSet values are :"+linkedHashSet);
    		System.out.println("TreeSet values are :"+treeSet);
    		
    	}
    
    }
    Output:
    HashSet values are :[Hi, 1Hi, 2Hi]
    linkedHashSet values are :[3Hi, 2Hi, Hi]
    TreeSet values are :[1Hi, 2Hi3, 3Hi2] // here if you obsereve , it was following order.
    
    

    Map

    java.util.Map is object which maps key to values(key and value both are objects), key is unique and for each key there only one value.Java contains three classes which implements Map interface , they are TreeMap (Gurantees Order), HashMap(we will use HashMap more)and LinkedHashMap.

    Some methods in Map
    1. void clear() - Remove all the mapping(keys and values).
    2. boolean containsKey()- Return tru if mapping contains specific key.
    3. entrySet() - Return set view of the mappings contained in map.
    4. int size() - Return size of Map.
    5. Set keySet() Returns set view of Key's in Mapping.-
    Possible Exceptions to be thrown
    1. NullPointerException -- if any of object is null.
    2. NoSuchElementException -- if there are no elements present where you are trying to get some values.
    3. ClassCastException -- if object is incompatable with elements.
    Example
    package com.collections.first;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class MapDemo {
    
    	public static void main(String[] args) {
    		Map map = new HashMap();
    		map.put(1,"Hi");
    		map.put(2, "Hello");
    		System.out.println("Map values are"+map);
    		System.out.println("is this containing 1?: "+map.containsKey(1));
    		System.out.println("i want to get value for key 2 : "+map.get(2));
    
    	}
    
    }
    Output:
    Map values are{1=Hi, 2=Hello}
    is this containing 1?: true
    i want to get value for key 2 : Hello
    

    Comparable vs Comparator

    Comparable
    1. Comparable interface gives natural sorting order
    2. Override compareTo() method
    3. Compares whether both are eual or not(not in length)
    Comparator
    1. Used for specific purpose
    2. Compares length of two strings
    3. It has compare() Method to compare two objects
    Note: For all information please check Oracle Documentation.