Professional Documents
Culture Documents
Collections in Java
Collections in java is a framework that provides an
architecture to store and manipulate the group of
objects.
searching,
sorting,
insertion,
manipulation,
deletion etc.
Set
List
Queue
Deque
etc.
classes
ArrayList
Vector
LinkedList
PriorityQueue
HashSet
LinkedHashSet
TreeSet .
No Method Description
.
element) element.
Iterator interface
Iterator interface provides the facility of iterating
the elements in forward direction only.
No Method Description
.
4. HashSet class
5. LinkedHashSet class
6. TreeSet class
7. PriorityQueue class
8. Map interface
9. HashMap class
13. Sorting
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable,
Serializable
Method Description
1. ArrayList al=new ArrayList();
//creating old non-generic arraylist
1. ArrayList<String> al=new ArrayList<String>();
//creating new generic arraylist
In generic collection,
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>();
//Creating arraylist
list.add("Ravi");
//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi
Vijay
Ravi
Ajay
1. By Iterator interface.
2. 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.
Ravi
Vijay
Ravi
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 16
IIHT Dehradun JSE(Collection)
Ajay
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
import java.util.*;
public class TestCollection3{
public static void main(String args[])
{
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s3=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);
//Getting Iterator
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 17
IIHT Dehradun JSE(Collection)
Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st
.age);
}
}
}
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
}
Ravi
Vijay
Ajay
Sonoo
Hanumat
Ravi
import java.util.*;
class Book
{
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String
publisher, int quantity)
{
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ArrayListExample
{
public static void main(String[] args)
{
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kan
etkar","BPB",8);
Book b2=new Book(102,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvi
n","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.auth
or+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc
Graw Hill 4
103 Operating System Galvin Wiley 6
public class LinkedList<E> extends
AbstractSequentialList<E> implements List<E>,
Deque<E>, Cloneable, Serializable
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author
+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc
Graw Hill 4
103 Operating System Galvin Wiley 6
ArrayList LinkedList
import java.util.*;
class TestArrayLinked
{
public static void main(String args[]){
List<String> al=new ArrayList<String>();
//creating arraylist
al.add("Ravi");
//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
List<String> al2=new LinkedList<String>();
//creating linkedlist
al2.add("James");
//adding object in linkedlist
al2.add("Serena");
al2.add("Swati");
al2.add("Junaid");
System.out.println("arraylist: "+al);
System.out.println("linkedlist: "+al2);
}
}
Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
Method Description
invoking list.
Output:
Element at 2nd position: Vijay
Amit
Sachin
Vijay
Kumar
Method Description
import java.util.*;
public class TestCollection8
{
public static void main(String args[])
{
ArrayList<String> al=new ArrayList<String>();
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
System.out.println("element at 2nd position: "+al.get
(2));
ListIterator<String> itr=al.listIterator();
System.out.println("traversing elements in forward d
irection...");
while(itr.hasNext())
{
System.out.println(itr.next());
}
System.out.println("traversing elements in backward
direction...");
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 35
IIHT Dehradun JSE(Collection)
while(itr.hasPrevious())
{
System.out.println(itr.previous());
}
}
}
Output:
element at 2nd position: Vijay
traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ListExample
{
public static void main(String[] args)
{
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kan
etkar","BPB",8);
Book b2=new Book(102,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvi
n","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author
+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 37
IIHT Dehradun JSE(Collection)
public class HashSet<E> extends AbstractSet<E>
implements Set<E>, Cloneable, Serializable
Constructor Description
Method Description
import java.util.*;
class TestCollection9{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ajay
Vijay
Ravi
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String
publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class HashSetExample {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kan
etkar","BPB",8);
Book b2=new Book(102,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvi
n","Wiley",6);
//Adding Books to HashSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing HashSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author
+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc
Graw Hill 4
103 Operating System Galvin Wiley 6
public class LinkedHashSet<E> extends HashSet<E
> implements Set<E>, Cloneable, Serializable
Constructor Description
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi
Vijay
Ajay
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kan
etkar","BPB",8);
Book b2=new Book(102,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvi
n","Wiley",6);
//Adding Books to hash table
hs.add(b1);
hs.add(b2);
hs.add(b3);
//Traversing hash table
for(Book b:hs){
System.out.println(b.id+" "+b.name+" "+b.author
+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc
Graw Hill 4
103 Operating System Galvin Wiley 6
public class TreeSet<E> extends AbstractSet<E> i
mplements NavigableSet<E>, Cloneable,
Serializable
Method Description
Output:
Ajay
Ravi
Vijay
import java.util.*;
class Book implements Comparable<Book>{
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String
publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
public int compareTo(Book b) {
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
}
}
public class TreeSetExample {
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 53
IIHT Dehradun JSE(Collection)
public static void main(String[] args) {
Set<Book> set=new TreeSet<Book>();
//Creating Books
Book b1=new Book(121,"Let us C","Yashwant Kan
etkar","BPB",8);
Book b2=new Book(233,"Operating System","Galvi
n","Wiley",6);
Book b3=new Book(101,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
//Adding Books to TreeSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing TreeSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author
+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Data Communications & Networking Forouzan Mc
Graw Hill 4
121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6
Method Description
PriorityQueue class
The PriorityQueue class provides the facility of
using queue.
public class PriorityQueue<E> extends
AbstractQueue<E> implements Serializable
queue.add("Rahul");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output:head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
import java.util.*;
class Book implements Comparable<Book>{
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String
publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
public int compareTo(Book b) {
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
}
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 58
IIHT Dehradun JSE(Collection)
}
public class LinkedListExample {
public static void main(String[] args) {
Queue<Book> queue=new PriorityQueue<Book>()
;
//Creating Books
Book b1=new Book(121,"Let us C","Yashwant Kan
etkar","BPB",8);
Book b2=new Book(233,"Operating System","Galvi
n","Wiley",6);
Book b3=new Book(101,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
//Adding Books to the queue
queue.add(b1);
queue.add(b2);
queue.add(b3);
System.out.println("Traversing the queue element
s:");
//Traversing queue elements
for(Book b:queue){
System.out.println(b.id+" "+b.name+" "+b.author
+" "+b.publisher+" "+b.quantity);
}
queue.remove();
System.out.println("After removing one book recor
d:");
for(Book b:queue){
System.out.println(b.id+" "+b.name+" "+b.auth
or+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
Traversing the queue elements:
101 Data Communications & Networking Forouzan Mc
Graw Hill 4
233 Operating System Galvin Wiley 6
121 Let us C Yashwant Kanetkar BPB 8
After removing one book record:
121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6
Java Deque Interface
Java Deque Interface is a linear collection that
supports element insertion and removal at both
ends.
Method Description
return
this deque,
deque is empty.
ArrayDeque class
The ArrayDeque class provides the facility of using
deque and resizable-array.
ArrayDeque Hierarchy
The hierarchy of ArrayDeque class is given in the
figure displayed at the right side of the page.
public class ArrayDeque<E> extends AbstractColl
ection<E> implements Deque<E>, Cloneable,
Serializable
{
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>(
);
deque.add("Ravi");
deque.add("Vijay");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}
Output:
Ravi
Vijay
Ajay
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s);
}
//deque.poll();
//deque.pollFirst();//it is same as poll()
deque.pollLast();
System.out.println("After pollLast() Traversal...");
for(String s:deque){
System.out.println(s);
}
}
}
Output:
After offerFirst Traversal...
jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal
int quantity;
public Book(int id, String name, String author, String
publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class ArrayDequeExample {
public static void main(String[] args) {
Deque<Book> set=new ArrayDeque<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kan
etkar","BPB",8);
Book b2=new Book(102,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvi
n","Wiley",6);
//Adding Books to Deque
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing ArrayDeque
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author
+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 66
IIHT Dehradun JSE(Collection)
Method Description
Map.Entry Interface
Entry is the sub interface of Map.
Method Description
Output:
102 Rahul
100 Amit
101 Vijay
//Non-generic
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
//Adding elements to map
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Set set=map.entrySet();//Converting to Set so tha
t we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get ke
y and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+"
"+entry.getValue());
}
}
}
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
public class HashMap<K,V> extends AbstractMap
<K,V> implements Map<K,V>, Cloneable,
Serializable
Constructor Description
this map.
101 Vijay
Output:
Values before remove: {102=Operating System,
103=Data Communication and Networking, 101=Let
us C}
Values after remove: {103=Data Communication and
Networking, 101=Let us C}
Book b3=new Book(103,"Operating System","Galvi
n","Wiley",6);
//Adding Books to map
map.put(1,b1);
map.put(2,b2);
map.put(3,b3);
//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet
()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.auth
or+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc
Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6
public class LinkedHashMap<K,V> extends Hash
Map<K,V> implements Map<K,V>
class TestCollection14{
public static void main(String args[]){
LinkedHashMap<Integer,String> hm=new LinkedHa
shMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:100 Amit
101 Vijay
102 Rahul
map.put(103, "Data Communication and Networkin
g");
System.out.println("Values before remove: "+ map
);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
}
}
Output:
Values before remove: {101=Let us C,
102=Operating System, 103=Data Communication and
Networking}
Values after remove: {101=Let us C, 103=Data
Communication and Networking}
public class MapExample {
public static void main(String[] args) {
//Creating map of Books
Map<Integer,Book> map=new LinkedHashMap<In
teger,Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kan
etkar","BPB",8);
Book b2=new Book(102,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvi
n","Wiley",6);
//Adding Books to map
map.put(2,b2);
map.put(1,b1);
map.put(3,b3);
//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet
()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.auth
or+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
2 Details:
public class TreeMap<K,V> extends AbstractMap<K
,V> implements NavigableMap<K,V>, Cloneable, Se
rializable
Constructor Description
Method Description
key.
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}
HashMap TreeMap
Book b2=new Book(102,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvi
n","Wiley",6);
//Adding Books to map
map.put(2,b2);
map.put(1,b1);
map.put(3,b3);
//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet
()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.auth
or+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc
Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6
public class Hashtable<K,V> extends Dictionary<K,
V> implements Map<K,V>, Cloneable, Serializable
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Int
eger,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
map.put(101, "Data Communication and Networkin
g");
System.out.println("Values before remove: "+ map
);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
}
}
Output:
Values before remove: {103=Operating System,
102=Let us C, 101=Data Communication and
Networking}
Values after remove: {103=Operating System,
101=Data Communication and Networking}
}
public class HashtableExample {
public static void main(String[] args) {
//Creating map of Books
Map<Integer,Book> map=new Hashtable<Integer,
Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kan
etkar","BPB",8);
Book b2=new Book(102,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvi
n","Wiley",6);
//Adding Books to map
map.put(1,b1);
map.put(2,b2);
map.put(3,b3);
//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet
()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.auth
or+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
3 Details:
103 Operating System Galvin Wiley 6
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 98
IIHT Dehradun JSE(Collection)
2 Details:
102 Data Communications & Networking Forouzan Mc
Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
HashMap Hashtable
8) HashMap Hashtable
inherits AbstractMap class. inherits Dictiona
ryclass.
public abstract class EnumSet<E extends Enum<E>
> extends AbstractSet<E> implements Cloneable, S
erializable
Method Description
the specified
element.
Output:
TUESDAY
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 103
IIHT Dehradun JSE(Collection)
WEDNESDAY
Output:
Week Days:[SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY]
Week Days:[]
public class EnumMap<K extends Enum<K>,V> ext
ends AbstractMap<K,V> implements Serializable, C
loneable
Constructor Description
Method Description
number of key-value
mappings in this map.
Output:
Monday 1
Tuesday 2
Wednesday 3
Thursday 4
// Adding Books to Map
map.put(Key.One, b1);
map.put(Key.Two, b2);
map.put(Key.Three, b3);
// Traversing EnumMap
for(Map.Entry<Key, Book> entry:map.entrySet()
){
Book b=entry.getValue();
System.out.println(b.id+" "+b.name+" "+b.au
thor+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
101 Let us C Yashwant Kanetkar BPB 8
102 Data Communications & Networking Forouzan Mc
Graw Hill 4
103 Operating System Galvin Wiley 6
public class Collections extends Object
Method Description
order induced by
the specified
comparator.
System.out.println("After adding elements collec
tion value:"+list);
String[] strArr = {"C#", ".Net"};
Collections.addAll(list, strArr);
System.out.println("After adding array collectio
n value:"+list);
}
}
Output:
Initial collection value:[C, Core Java, Advance
Java]
After adding elements collection value:[C, Core
Java, Advance Java, Servlet, JSP]
After adding array collection value:[C, Core
Java, Advance Java, Servlet, JSP, C#, .Net]
Output:
Value of maximum element from the collection: 67
Output:
Value of minimum element from the collection: 8
Sorting in Collection
1.String objects
2.Wrapper class objects
3.User-defined class objects
Note:
import java.util.*;
class TestSort1{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Viru");
al.add("Saurav");
al.add("Mukesh");
al.add("Tahir");
Collections.sort(al);
Iterator itr=al.iterator();
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 116
IIHT Dehradun JSE(Collection)
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:Mukesh
Saurav
Tahir
Viru
import java.util.*;
class TestSort2{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(Integer.valueOf(201));
al.add(Integer.valueOf(101));
al.add(230);//internally will be converted into object
s as Integer.valueOf(230)
Collections.sort(al);
Iterator itr=al.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:101
201
230
1.String objects
2.Wrapper class objects
Collections class
Collections class provides static methods for
sorting the elements of collections.
Note:
File: Student.java
class Student implements Comparable<Student>{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
public int compareTo(Student st){
if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}
File: TestSort3.java
import java.util.*;
import java.io.*;
public class TestSort3{
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 120
IIHT Dehradun JSE(Collection)
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age
);
}
}
}
Output:105 Jai 21
101 Vijay 23
106 Ajay 27
compare() method
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 121
IIHT Dehradun JSE(Collection)
Collections class
Collections class provides static methods for
sorting the elements of collection.
1.Student.java
2.AgeComparator.java
3.NameComparator.java
4.Simple.java
Student.java
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
AgeComparator.java
import java.util.*;
class AgeComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 123
IIHT Dehradun JSE(Collection)
Student s2=(Student)o2;
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
NameComparator.java
import java.util.*;
class NameComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.name.compareTo(s2.name);
}
}
Simple.java
import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
System.out.println("Sorting by Name...");
Collections.sort(al,new NameComparator());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age
);
}
System.out.println("sorting by age...");
Collections.sort(al,new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st.rollno+" "+st.name+" "+st.age
);
}
}
}
Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
AgeComparator.java
import java.util.*;
class AgeComparator implements Comparator<Stude
nt>{
public int compare(Student s1,Student s2){
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 126
IIHT Dehradun JSE(Collection)
return -1;
}
}
NameComparator.java
import java.util.*;
class NameComparator implements Comparator<Stud
ent>{
public int compare(Student s1,Student s2){
return s1.name.compareTo(s2.name);
}
}
Simple.java
import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
System.out.println("Sorting by Name...");
Collections.sort(al,new NameComparator());
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age
);
}
System.out.println("sorting by age...");
Collections.sort(al,new AgeComparator());
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age
);
}
}
}
Output:Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
Method Description
db.properties
user=system
password=oracle
Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exceptio
n{
FileReader reader=new FileReader("db.properties"
);
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output:system
oracle
Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exceptio
n{
Properties p=System.getProperties();
Set set=p.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" =
"+entry.getValue());
}
}
}
Output:
java.runtime.name = Java(TM) SE Runtime
Environment
sun.boot.library.path = C:\Program
Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 132
IIHT Dehradun JSE(Collection)
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........
Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exceptio
n{
Properties p=new Properties();
p.setProperty("name","Sonoo Jaiswal");
p.setProperty("email","sonoojaiswal@javatpoint.com
");
p.store(new FileWriter("info.properties"),"Javatpoint
Properties Example");
}
}
info.properties
#Java Properties Example
#Thu Oct 03 22:35:53 IST 2013
email=sonoojaiswal@java.com
name=Sonoo Jaiswal
ArrayList Vector
2) Vector increments
ArrayList increment 100% means doubles the
s 50%of current array size if total number
array size if number of element exceeds than
of element exceeds its capacity.
from its capacity.
introduced in JDK
1.2.
5) ArrayList Vector
uses Iteratorinterfa uses Enumeration interfa
ce to traverse the ce to traverse the
elements. elements. But it can use
Iterator also.
import java.util.*;
class TestArrayList21{
public static void main(String args[]){
List<String> al=new ArrayList<String>();//creatin
g arraylist
al.add("Sonoo");//adding object in arraylist
al.add("Michael");
al.add("James");
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 135
IIHT Dehradun JSE(Collection)
al.add("Andy");
//traversing elements using Iterator
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Sonoo
Michael
James
Andy
import java.util.*;
class TestVector1{
public static void main(String args[]){
Vector<String> v=new Vector<String>();//creating
vector
v.add("umesh");//method of Collection
v.addElement("irfan");//method of Vector
v.addElement("kumar");
//traversing elements using Enumeration
Enumeration e=v.elements();
while(e.hasMoreElements()){
System.out.println(e.nextElement());
}
By:-Pradip Shivaji Tangade
Pradiptangade333@gmail.com Page 136
IIHT Dehradun JSE(Collection)
}
}