Collections in Java
Collections :
List is an interface and it contains
Classes of ArrayList and Linked List.
Iterator interface
Iterator interface provides the facility of iterating the
elements in forward direction only.
|
Methods of Iterator interface
There are only three methods in
the Iterator interface. They are:
- public boolean hasNext() it returns true if iterator has more
elements.
- public object next() it returns the element and moves the
cursor pointer to the next element.
- public void remove() it removes the last elements returned
by the iterator. It is rarely used.
ArrayList
class
Java ArrayList class uses a
dynamic array for storing the elements. It inherits AbstractList class and
implements List interface.
The important points about Java
ArrayList class are:
- Java ArrayList class can contain
duplicate elements.
- Java ArrayList class maintains
insertion order.
- Java ArrayList class is non
synchronized.
- Java ArrayList allows random access
because array works at the index basis.
- In Java ArrayList class, manipulation
is slow because a lot of shifting needs to be occurred if any element is
removed from the array list.
Sample Program:
1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
OutPut:
Ravi
Vijay
Ravi
Ajay
Two ways to iterate the elements of
collection in java
There are two ways to traverse
collection elements:
- By Iterator interface.
- By for-each loop.
In the above example, we have
seen traversing ArrayList by Iterator. Let's see the example to traverse
ArrayList elements using for-each loop.
1. import java.util.*;
2. class TestCollection2{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. for(String obj:al)
10. System.out.println(obj);
11. }
12. }
OutPut:
Ravi
Vijay
Ravi
Ajay
Example of addAll(Collection c)
method:
1. import java.util.*;
2. class TestCollection4{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Sonoo");
10. al2.add("Hanumat");
11. al.addAll(al2);//adding second list in first list
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Output:
Ravi
Vijay
Ajay
Sonoo
Hanumat
Example of removeAll() method:
1. import java.util.*;
2. class TestCollection5{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11. al.removeAll(al2);
12. System.out.println("iterating the elements after removing the elements of al2...");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17.
18. }
19. }
Output:
iterating the elements after removing the elements of al2…
Vijay
Ajay
LinkedList
class
The
important points about Java LinkedList are:
- Java
LinkedList class can contain duplicate elements.
- Java
LinkedList class maintains insertion order.
- Java
LinkedList class is non synchronized.
- In Java
LinkedList class, manipulation is fast because no shifting needs to be
occurred.
- Java
LinkedList class can be used as list, stack or queue.
LinkedList Example
1. import java.util.*;
2. public class TestCollection{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ravi
Vijay
Ravi
Ajay
Linked List
Example:
package oops;
import
java.util.LinkedList;
public class TestCollection
{
public static void main(String[]
args) {
LinkedList
<String>li=new LinkedList<String>();
li.add("Ajay");
li.addLast("Hari");
li.add("Bala");
li.addFirst("Satish");
String
s1=li.getFirst();
System.out.println("The
First element is "+s1);
for(String s: li)
{
System.out.println("The
elements in the list are "+s);
}
}
}
Output:
The First element is Satish
The elements in the list are Satish
The elements in the list are Ajay
The elements in the list are Hari
The elements in the list are Bala
Queue:
Java
Queue interface orders the element in FIFO(First In First Out) manner. In FIFO,
first element is removed first and last element is removed at last.
Object poll():
It is used to retrieves
and removes the head of this queue, or returns null if this queue is empty.
Queue Interface declaration:
public interface Queue<E> extends Collection<E>
Example:
1. import java.util.*;
2. class TestCollection12{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit");
6. queue.add("Vijay");
7. queue.add("Karan");
8. queue.add("Jai");
9. queue.add("Rahul");
10. System.out.println("head:"+queue.element());
11. System.out.println("head:"+queue.peek());
12. System.out.println("iterating the queue elements:");
13. Iterator itr=queue.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17. queue.remove();
18. queue.poll();
19. System.out.println("after removing two elements:");
20. Iterator<String> itr2=queue.iterator();
21. while(itr2.hasNext()){
22. System.out.println(itr2.next());
23. }
24. }
25. }
Output:
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
Set:
Set is an
interface,In set the classes are Hashset and
Treeset.
Java
HashSet class is used to create a collection that uses a hash table for
storage. It inherits the AbstractSet class and implements Set interface.
The
important points about Java HashSet class are:
- HashSet
stores the elements by using a mechanism called hashing.
- HashSet
contains unique elements only.
1. import java.util.*;
2. class TestCollection9{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ajay
Vijay
Ravi
TreeSet
Java
TreeSet class implements the Set interface that uses a tree for storage. It
inherits AbstractSet class and implements NavigableSet interface. The objects
of TreeSet class are stored in ascending order.
The
important points about Java TreeSet class are:
- Contains
unique elements only like HashSet.
- Access
and retrieval times are quiet fast.
- Maintains
ascending order.
import java.util.*;
class
TestCollection9{
public static void main(String
args[]){
//Creating HashSet and adding elements
TreeSet<Integer> al=new
TreeSet<Integer>();
al.add(100);
al.add(98);
al.add(67);
al.add(50);
//Traversing elements
Iterator<Integer>
itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
50
67
98
100
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
System.out.println("Tree Set Example!\n");
TreeSet<Integer> tree = new TreeSet<Integer>();
tree.add(12);
tree.add(63);
tree.add(34);
tree.add(45);
// here it test it's sorted, 63 is
the last element. see output below
Iterator<Integer> iterator = tree.iterator();
System.out.print("Tree set data: ");
// Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
// Check empty or not
if (tree.isEmpty()) {
System.out.print("Tree Set is empty.");
} else {
System.out.println("Tree Set size: " + tree.size());
}
// Retrieve first data from tree set
System.out.println("First data: " + tree.first());
// Retrieve last data from tree set
System.out.println("Last data: " + tree.last());
if (tree.remove(45)) { // remove element by value
System.out.println("Data is removed from tree set");
} else {
System.out.println("Data doesn't exist!");
}
System.out.print("Now the tree set contain: ");
iterator = tree.iterator();
// Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println();
System.out.println("Now the size of tree set: " + tree.size());
// Remove all
tree.clear();
if (tree.isEmpty()) {
System.out.print("Tree Set is empty.");
} else {
System.out.println("Tree Set size: " + tree.size());
}
}
}
Output:
Treeset Example
Tree set Data :12 34
45 63
Tree set size : 4
First Data: 12
Last Data: 63
Data is removed from
the Treeset
Now the tree set contain : 12 34 63
Now the size of tree
set : 3
Tree set is Empty.
HashMap:
Java
HashMap class implements the map interface by using a hashtable. It inherits
AbstractMap class and implements Map interface.
The
important points about Java HashMap class are:
- A
HashMap contains values based on the key.
- It
contains only unique elements.
- It may
have one null key and multiple null values.
- It
maintains no order.
HashMap class Parameters
Let's see the Parameters for
java.util.HashMap class.
- K: It is the type of keys
maintained by this map.
- V: It is the type of mapped
values.
Methods:
Set entrySet() : It is used to return a collection view of
the mappings contained in this map.
Set keyset() : It is used to
return a set view of the keys contained in this map.
1. import java.util.*;
2. class TestCollection13{
3. public static void main(String args[]){
4. HashMap<Integer,String> hm=new HashMap<Integer,String>();
5. hm.put(100,"Amit");
6. hm.put(101,"Vijay");
7. hm.put(102,"Rahul");
8. for(Map.Entry m:hm.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue());
10. }
11. }
12. }
Output :
102 Rahul
100 Amit
101 Vijay
import
java.util.HashMap;
import
java.util.Map;
import
java.util.Iterator;
import
java.util.Set;
public class Details {
public static void
main(String args[]) {
/* This is how to declare HashMap */
HashMap<Integer, String>
hmap = new HashMap<Integer, String>();
/*Adding elements to HashMap*/
hmap.put(12, "Chaitanya");
hmap.put(2, "Rahul");
hmap.put(7, "Singh");
hmap.put(49, "Ajeet");
hmap.put(3, "Anuj");
/* Display content using Iterator*/
Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key
is: "+ mentry.getKey() + " & Value is: ");
System.out.println(mentry.getValue());
}
/* Get values based on key*/
String var=
hmap.get(2);
System.out.println("Value
at index 2 is: "+var);
/* Remove values based on key*/
hmap.remove(3);
System.out.println("Map
key and values after removal:");
Set set2 = hmap.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry
mentry2 = (Map.Entry)iterator2.next();
System.out.print("Key
is: "+mentry2.getKey() + " & Value is: ");
System.out.println(mentry2.getValue());
}
}
}
Output:
key is: 49 &
Value is: Ajeet
key is: 2
& Value is: Rahul
key is: 3
& Value is: Anuj
key is: 7
& Value is: Singh
key is: 12
& Value is: Chaitanya
Value at
index 2 is: Rahul
Map key
and values after removal:
Key is: 49
& Value is: Ajeet
Key is: 2
& Value is: Rahul
Key is: 7
& Value is: Singh
Key is: 12
& Value is: Chaitanya
The Map.Entry interface enables you to work with a
map entry.
The entrySet( ) method declared by
the Map interface returns a Set containing the map entries. Each of these set
elements is a Map.Entry object.
TreeMap:
Java
TreeMap class implements the Map interface by using a tree. It provides an
efficient means of storing key/value pairs in sorted order.
The
important points about Java TreeMap class are:
- A
TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
- It
contains only unique elements.
- It
cannot have null key but can have multiple null values.
- It is
same as HashMap instead maintains ascending order.
Example:
1. import java.util.*;
2. public class TreeMapExample {
3. public static void main(String args[]) {
4. // Create and populate tree map
5. Map<Integer, String> map = new TreeMap<Integer, String>();
6. map.put(102,"Let us C");
7. map.put(103, "Operating System");
8. map.put(101, "Data Communication and Networking");
9. System.out.println("Values before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("Values after remove: "+ map);
13. }
14. }
Output:
Values before remove: {101=Data
Communication and Networking, 102=Let us C, 103=Operating System}
Values after remove: {101=Data
Communication and Networking, 103=Operating System}
0 comments:
Post a Comment