Unit 4 Java
Unit 4 Java
Set Interface in Java is present in java.util package. It extends the Collection interface.
It represents the unordered set of elements which doesn't allow us to store the
duplicate items. We can store at most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet.
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its
elements. The elements of the SortedSet are arranged in the increasing (ascending)
order. The SortedSet provides the additional methods that inhibit the natural
ordering of the elements.
TreeSet(Collection<? extends It is used to build a new tree set that contains the
E> c) elements of the collection c.
TreeSet(Comparator<? super It is used to construct an empty tree set that will be sorted
E> comparator) according to given comparator.
Method Description
boolean addAll(Collection<? extends E> c) It is used to add all of the elements in the
specified collection to this set.
NavigableSet headSet(E toElement, boolean It returns the group of elements that are
inclusive) less than or equal to(if, inclusive is true) the
specified element.
NavigableSet subSet(E fromElement, boolean It returns a set of elements that lie between
fromInclusive, E toElement, boolean toInclusive) the given range.
SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie between
the given range which includes
fromElement and excludes toElement.
NavigableSet tailSet(E fromElement, boolean It returns a set of elements that are greater
inclusive) than or equal to (if, inclusive is true) the
specified element.
FileName: TreeSet1.java
1. import java.util.*;
2. class TreeSet1{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ajay
Ravi
Vijay
FileName: TreeSet2.java
1. import java.util.*;
2. class TreeSet2{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ajay");
8. System.out.println("Traversing element through Iterator in descending order");
9. Iterator i=set.descendingIterator();
10. while(i.hasNext())
11. {
12. System.out.println(i.next());
13. }
14.
15. }
16. }
Output:
FileName: TreeSet3.java
1. import java.util.*;
2. class TreeSet3{
3. public static void main(String args[]){
4. TreeSet<Integer> set=new TreeSet<Integer>();
5. set.add(24);
6. set.add(66);
7. set.add(12);
8. set.add(15);
9. System.out.println("Lowest Value: "+set.pollFirst());
10. System.out.println("Highest Value: "+set.pollLast());
11. }
12. }
Output:
Lowest Value: 12
Highest Value: 66
FileName: TreeSet4.java
1. import java.util.*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("A");
6. set.add("B");
7. set.add("C");
8. set.add("D");
9. set.add("E");
10. System.out.println("Initial Set: "+set);
11.
12. System.out.println("Reverse Set: "+set.descendingSet());
13.
14. System.out.println("Head Set: "+set.headSet("C", true));
15.
16. System.out.println("SubSet: "+set.subSet("A", false, "E", true));
17.
18. System.out.println("TailSet: "+set.tailSet("C", false));
19. }
20. }
Output:
FileName: TreeSet5.java
1. import java.util.*;
2. class TreeSet5{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. set.add("A");
6. set.add("B");
7. set.add("C");
8. set.add("D");
9. set.add("E");
10.
11. System.out.println("Intial Set: "+set);
12.
13. System.out.println("Head Set: "+set.headSet("C"));
14.
15. System.out.println("SubSet: "+set.subSet("A", "E"));
16.
17. System.out.println("TailSet: "+set.tailSet("C"));
18. }
19. }
Output:
FileName: TreeSetExample.java
1. import java.util.*;
2. class Book implements Comparable<Book>{
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. // implementing the abstract method
14. public int compareTo(Book b) {
15. if(id>b.id){
16. return 1;
17. }else if(id<b.id){
18. return -1;
19. }else{
20. return 0;
21. }
22. }
23. }
24. public class TreeSetExample {
25. public static void main(String[] args) {
26. Set<Book> set=new TreeSet<Book>();
27. //Creating Books
28. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
29. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
30. Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Gr
aw Hill",4);
31. //Adding Books to TreeSet
32. set.add(b1);
33. set.add(b2);
34. set.add(b3);
35. //Traversing TreeSet
36. for(Book b:set){
37. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qu
antity);
38. }
39. }
40. }
Output:
FileName: ClassCastExceptionTreeSet.java
Java LinkedHashMap class is Hashtable and Linked list implementation of the Map
interface, with predictable iteration order. It inherits HashMap class and implements
the Map interface.
Points to remember
Constructor Description
Method Description
void forEach(BiConsumer<? super K,? It performs the given action for each entry
super V> action) in the map until all entries have been
processed or the action throws an
exception.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the
super V,? extends V> function) result of invoking the given function on
that entry until all entries have been
processed or the function throws an
exception.
1. import java.util.*;
2. class LinkedHashMap1{
3. public static void main(String args[]){
4.
5. LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>(
);
6.
7. hm.put(100,"Amit");
8. hm.put(101,"Vijay");
9. hm.put(102,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Output:100 Amit
101 Vijay
102 Rahul
1. import java.util.*;
2. class LinkedHashMap2{
3. public static void main(String args[]){
4. LinkedHashMap<Integer, String> map = new LinkedHashMap<Integer, Stri
ng>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. //Fetching key
9. System.out.println("Keys: "+map.keySet());
10. //Fetching value
11. System.out.println("Values: "+map.values());
12. //Fetching key-value pair
13. System.out.println("Key-Value pairs: "+map.entrySet());
14. }
15. }
Keys: [100, 101, 102]
Values: [Amit, Vijay, Rahul]
Key-Value pairs: [100=Amit, 101=Vijay, 102=Rahul]
1. import java.util.*;
2. public class LinkedHashMap3 {
3. public static void main(String args[]) {
4. Map<Integer,String> map=new LinkedHashMap<Integer,String>();
5. map.put(101,"Amit");
6. map.put(102,"Vijay");
7. map.put(103,"Rahul");
8. System.out.println("Before invoking remove() method: "+map);
9. map.remove(102);
10. System.out.println("After invoking remove() method: "+map);
11. }
12. }
Output:
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class MapExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new LinkedHashMap<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan",
"Mc Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(2,b2);
24. map.put(1,b1);
25. map.put(3,b3);
26.
27. //Traversing map
28. for(Map.Entry<Integer, Book> entry:map.entrySet()){
29. int key=entry.getKey();
30. Book b=entry.getValue();
31. System.out.println(key+" Details:");
32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.
quantity);
33. }
34. }
35. }
Output:
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
3 Details:
103 Operating System Galvin Wiley 6
Constructor Description
Method Description
Map.Entry<K,V> ceilingEntry(K key) It returns the key-value pair having the least
key, greater than or equal to the specified
key, or null if there is no such key.
Comparator<? super K> comparator() It returns the comparator that arranges the
key in order, or null if the map uses the
natural ordering.
Map.Entry<K,V> floorEntry(K key) It returns the greatest key, less than or equal
to the specified key, or null if there is no such
key.
void forEach(BiConsumer<? super K,? It performs the given action for each entry in
super V> action) the map until all entries have been processed
or the action throws an exception.
SortedMap<K,V> headMap(K toKey) It returns the key-value pairs whose keys are
strictly less than toKey.
NavigableMap<K,V> headMap(K It returns the key-value pairs whose keys are
toKey, boolean inclusive) less than (or equal to if inclusive is true)
toKey.
Map.Entry<K,V> higherEntry(K key) It returns the least key strictly greater than
the given key, or null if there is no such key.
void putAll(Map<? extends K,? extends It is used to copy all the key-value pair from
V> map) one map to another map.
boolean replace(K key, V oldValue, V It replaces the old value with the new value
newValue) for a specified key.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result
super V,? extends V> function) of invoking the given function on that entry
until all entries have been processed or the
function throws an exception.
boolean containsValue(Object value) It returns true if the map maps one or more
keys to the specified value.
1. import java.util.*;
2. class TreeMap1{
3. public static void main(String args[]){
4. TreeMap<Integer,String> map=new TreeMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9.
10. for(Map.Entry m:map.entrySet()){
11. System.out.println(m.getKey()+" "+m.getValue());
12. }
13. }
14. }
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul
1. import java.util.*;
2. public class TreeMap2 {
3. public static void main(String args[]) {
4. TreeMap<Integer,String> map=new TreeMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9. System.out.println("Before invoking remove() method");
10. for(Map.Entry m:map.entrySet())
11. {
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. map.remove(102);
15. System.out.println("After invoking remove() method");
16. for(Map.Entry m:map.entrySet())
17. {
18. System.out.println(m.getKey()+" "+m.getValue());
19. }
20. }
21. }
Output:
1. import java.util.*;
2. class TreeMap3{
3. public static void main(String args[]){
4. NavigableMap<Integer,String> map=new TreeMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9. //Maintains descending order
10. System.out.println("descendingMap: "+map.descendingMap());
11. //Returns key-
value pairs whose keys are less than or equal to the specified key.
12. System.out.println("headMap: "+map.headMap(102,true));
13. //Returns key-
value pairs whose keys are greater than or equal to the specified key.
14. System.out.println("tailMap: "+map.tailMap(102,true));
15. //Returns key-value pairs exists in between the specified key.
16. System.out.println("subMap: "+map.subMap(100, false, 102, true));
17. }
18. }
descendingMap: {103=Rahul, 102=Ravi, 101=Vijay, 100=Amit}
headMap: {100=Amit, 101=Vijay, 102=Ravi}
tailMap: {102=Ravi, 103=Rahul}
subMap: {101=Vijay, 102=Ravi}
1. import java.util.*;
2. class TreeMap4{
3. public static void main(String args[]){
4. SortedMap<Integer,String> map=new TreeMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9. //Returns key-value pairs whose keys are less than the specified key.
10. System.out.println("headMap: "+map.headMap(102));
11. //Returns key-
value pairs whose keys are greater than or equal to the specified key.
12. System.out.println("tailMap: "+map.tailMap(102));
13. //Returns key-value pairs exists in between the specified key.
14. System.out.println("subMap: "+map.subMap(100, 102));
15. }
16. }
headMap: {100=Amit, 101=Vijay}
tailMap: {102=Ravi, 103=Rahul}
subMap: {100=Amit, 101=Vijay}
HashMap TreeMap
1) HashMap can contain one null key. TreeMap cannot contain any null key.
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class MapExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new TreeMap<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan",
"Mc Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(2,b2);
24. map.put(1,b1);
25. map.put(3,b3);
26.
27. //Traversing map
28. for(Map.Entry<Integer, Book> entry:map.entrySet()){
29. int key=entry.getKey();
30. Book b=entry.getValue();
31. System.out.println(key+" Details:");
32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.
quantity);
33. }
34. }
35. }
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
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of the
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Hashtable(int capacity) It accepts an integer parameter and creates a hash table that
contains a specified initial capacity.
Hashtable(int capacity, float It is used to create a hash table having the specified initial
loadFactor) capacity and loadFactor.
Hashtable(Map<? extends K,? It creates a new hash table with the same mappings as the
extends V> t) given Map.
Method Description
V compute(K key, BiFunction<? super It is used to compute a mapping for the specified
K,? super V,? extends V> key and its current mapped value (or null if there is
remappingFunction) no current mapping).
V computeIfAbsent(K key, Function<? It is used to compute its value using the given
super K,? extends V> mapping function, if the specified key is not already
mappingFunction) associated with a value (or is mapped to null), and
enters it into this map unless null.
void forEach(BiConsumer<? super K,? It performs the given action for each entry in the
super V> action) map until all entries have been processed or the
action throws an exception.
int hashCode() It returns the hash code value for the Map
V merge(K key, V value, BiFunction<? If the specified key is not already associated with a
super V,? super V,? extends V> value or is associated with null, associates it with the
remappingFunction) given non-null value.
V put(K key, V value) It inserts the specified value with the specified key
in the hash table.
void putAll(Map<? extends K,? extends It is used to copy all the key-value pair from map to
V> t)) hashtable.
V putIfAbsent(K key, V value) If the specified key is not already associated with a
value (or is mapped to null) associates it with the
given value and returns null, else returns the current
value.
boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the hashtable.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a
newValue) specified key.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of
super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function throws
an exception.
boolean contains(Object value) This method returns true if some value equal to the
value exists within the hash table, else return false.
boolean containsValue(Object value) This method returns true if some value equal to the
value exists within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the
key exists within the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empty;
returns false if it contains at least one key.
protected void rehash() It is used to increase the size of the hash table and
rehashes all of its keys.
V get(Object key) This method returns the object that contains the
value associated with the key.
V remove(Object key) It is used to remove the key and its value. This
method returns the value associated with the key.
1. import java.util.*;
2. class Hashtable1{
3. public static void main(String args[]){
4. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
5.
6. hm.put(100,"Amit");
7. hm.put(102,"Ravi");
8. hm.put(101,"Vijay");
9. hm.put(103,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Output:
1. import java.util.*;
2. class Hashtable3{
3. public static void main(String args[]){
4. Hashtable<Integer,String> map=new Hashtable<Integer,String>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9. //Here, we specify the if and else statement as arguments of the method
10. System.out.println(map.getOrDefault(101, "Not Found"));
11. System.out.println(map.getOrDefault(105, "Not Found"));
12. }
13. }
Output:
Vijay
Not Found
Java Hashtable Example: putIfAbsent()
1. import java.util.*;
2. class Hashtable4{
3. public static void main(String args[]){
4. Hashtable<Integer,String> map=new Hashtable<Integer,String>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9. System.out.println("Initial Map: "+map);
10. //Inserts, as the specified pair is unique
11. map.putIfAbsent(104,"Gaurav");
12. System.out.println("Updated Map: "+map);
13. //Returns the current value, as the specified pair already exist
14. map.putIfAbsent(101,"Vijay");
15. System.out.println("Updated Map: "+map);
16. }
17. }
Output:
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class HashtableExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new Hashtable<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Gr
aw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(1,b1);
24. map.put(2,b2);
25. map.put(3,b3);
26. //Traversing map
27. for(Map.Entry<Integer, Book> entry:map.entrySet()){
28. int key=entry.getKey();
29. Book b=entry.getValue();
30. System.out.println(key+" Details:");
31. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.
quantity);
32. }
33. }
34. }
Output:
3 Details:
103 Operating System Galvin Wiley 6
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
Sorting in Collection
We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of a collection. If collection elements are
use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the
elements.
Note: String class and Wrapper classes implement the Comparable interface. So if you
store the objects of string or wrapper classes, it will be Comparable.
1. import java.util.*;
2. class TestSort1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Viru");
7. al.add("Saurav");
8. al.add("Mukesh");
9. al.add("Tahir");
10.
11. Collections.sort(al);
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
Mukesh
Saurav
Tahir
Viru
1. import java.util.*;
2. class TestSort3{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add(Integer.valueOf(201));
7. al.add(Integer.valueOf(101));
8. al.add(230);//internally will be converted into objects as Integer.valueOf(230)
9.
10. Collections.sort(al);
11.
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
101
201
230
1. import java.util.*;
2.
3. class Student implements Comparable<Student> {
4. public String name;
5. public Student(String name) {
6. this.name = name;
7. }
8. public int compareTo(Student person) {
9. return name.compareTo(person.name);
10.
11. }
12. }
13. public class TestSort4 {
14. public static void main(String[] args) {
15. ArrayList<Student> al=new ArrayList<Student>();
16. al.add(new Student("Viru"));
17. al.add(new Student("Saurav"));
18. al.add(new Student("Mukesh"));
19. al.add(new Student("Tahir"));
20.
21. Collections.sort(al);
22. for (Student s : al) {
23. System.out.println(s.name);
24. }
25. }
26. }
Mukesh
Saurav
Tahir
Viru
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of
any data member, for example, rollno, name, age or anything else.
Method Description
public int compare(Object obj1, It compares the first object with the second object.
Object obj2)
public boolean equals(Object obj) It is used to compare the current object with the
specified object.
public boolean equals(Object obj) It is used to compare the current object with the
specified object.
Collections class
Collections class provides static methods for sorting the elements of a collection. If
collection elements are of Set or Map, we can use TreeSet or TreeMap. However, we
cannot sort the elements of List. Collections class provides methods for sorting the
elements of List type elements also.
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java
Student.java
This class contains three fields rollno, name and age and a parameterized
constructor.
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java
This class defines comparison logic based on the age. If the age of the first object is
greater than the second, we are returning a positive value. It can be anyone such as
1, 2, 10. If the age of the first object is less than the second object, we are returning a
negative value, it can be any negative value, and if the age of both objects is equal,
we are returning 0.
1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using
the compareTo() method of String class, which internally provides the comparison
logic.
1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }
Simple.java
In this class, we are printing the values of the object by sorting on the basis of name
and age.
1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. System.out.println("Sorting by Name");
13.
14. Collections.sort(al,new NameComparator());
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20.
21. System.out.println("Sorting by age");
22.
23. Collections.sort(al,new AgeComparator());
24. Iterator itr2=al.iterator();
25. while(itr2.hasNext()){
26. Student st=(Student)itr2.next();
27. System.out.println(st.rollno+" "+st.name+" "+st.age);
28. }
29.
30.
31. }
32. }
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age
105 Jai 21
101 Vijay 23
106 Ajay 27
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java
1. import java.util.*;
2. class AgeComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. if(s1.age==s2.age)
5. return 0;
6. else if(s1.age>s2.age)
7. return 1;
8. else
9. return -1;
10. }
11. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using
the compareTo() method of String class, which internally provides the comparison
logic.
1. import java.util.*;
2. class NameComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. return s1.name.compareTo(s2.name);
5. }
6. }
Simple.java
In this class, we are printing the values of the object by sorting on the basis of name
and age.
1. import java.util.*;
2. import java.io.*;
3. class Simple{
4. public static void main(String args[]){
5.
6. ArrayList<Student> al=new ArrayList<Student>();
7. al.add(new Student(101,"Vijay",23));
8. al.add(new Student(106,"Ajay",27));
9. al.add(new Student(105,"Jai",21));
10.
11. System.out.println("Sorting by Name");
12.
13. Collections.sort(al,new NameComparator());
14. for(Student st: al){
15. System.out.println(st.rollno+" "+st.name+" "+st.age);
16. }
17.
18. System.out.println("Sorting by age");
19.
20. Collections.sort(al,new AgeComparator());
21. for(Student st: al){
22. System.out.println(st.rollno+" "+st.name+" "+st.age);
23. }
24. }
25. }
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
int compare(T o1, T o2) It compares the first object with
second object.
static <T,U extends Comparable<? super U>> It accepts a function that extracts a
Comparator<T> comparing(Function<? super T,? Comparable sort key from a type T,
extends U> keyExtractor) and returns a Comparator that
compares by that sort key.
static <T extends Comparable<? super T>> It returns comparator that contains
Comparator<T> reverseOrder() reverse of natural ordering.
File: Student.java
1. class Student {
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10.
11. public int getRollno() {
12. return rollno;
13. }
14.
15. public void setRollno(int rollno) {
16. this.rollno = rollno;
17. }
18.
19. public String getName() {
20. return name;
21. }
22.
23. public void setName(String name) {
24. this.name = name;
25. }
26.
27. public int getAge() {
28. return age;
29. }
30.
31. public void setAge(int age) {
32. this.age = age;
33. }
34.
35. }
File: TestSort1.java
1. import java.util.*;
2. public class TestSort1{
3. public static void main(String args[]){
4. ArrayList<Student> al=new ArrayList<Student>();
5. al.add(new Student(101,"Vijay",23));
6. al.add(new Student(106,"Ajay",27));
7. al.add(new Student(105,"Jai",21));
8. /Sorting elements on the basis of name
9. Comparator<Student> cm1=Comparator.comparing(Student::getName);
10. Collections.sort(al,cm1);
11. System.out.println("Sorting by Name");
12. for(Student st: al){
13. System.out.println(st.rollno+" "+st.name+" "+st.age);
14. }
15. //Sorting elements on the basis of age
16. Comparator<Student> cm2=Comparator.comparing(Student::getAge);
17. Collections.sort(al,cm2);
18. System.out.println("Sorting by Age");
19. for(Student st: al){
20. System.out.println(st.rollno+" "+st.name+" "+st.age);
21. }
22. }
23. }
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by Age
105 Jai 21
101 Vijay 23
106 Ajay 27
File: Student.java
1. class Student {
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. public int getRollno() {
11. return rollno;
12. }
13. public void setRollno(int rollno) {
14. this.rollno = rollno;
15. }
16. public String getName() {
17. return name;
18. }
19.
20. public void setName(String name) {
21. this.name = name;
22. }
23.
24. public int getAge() {
25. return age;
26. }
27. public void setAge(int age) {
28. this.age = age;
29. }
30. }
File: TestSort2.java
1. import java.util.*;
2. public class TestSort2{
3. public static void main(String args[]){
4. ArrayList<Student> al=new ArrayList<Student>();
5. al.add(new Student(101,"Vijay",23));
6. al.add(new Student(106,"Ajay",27));
7. al.add(new Student(105,null,21));
8. Comparator<Student> cm1=Comparator.comparing(Student::getName,Comparator.
nullsFirst(String::compareTo));
9. Collections.sort(al,cm1);
10. System.out.println("Considers null to be less than non-null");
11. for(Student st: al){
12. System.out.println(st.rollno+" "+st.name+" "+st.age);
13. }
14. Comparator<Student> cm2=Comparator.comparing(Student::getName,Comparator.
nullsLast(String::compareTo));
15. Collections.sort(al,cm2);
16. System.out.println("Considers null to be greater than non-null");
17. for(Student st: al){
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }
Considers null to be less than non-null
105 null 21
106 Ajay 27
101 Vijay 23
Considers null to be greater than non-null
106 Ajay 27
101 Vijay 23
105 null 21
Collections in Java
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Do You Know?
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
1 public boolean It returns true if the iterator has more elements otherwise it
hasNext() returns false.
2 public Object next() It returns the element and moves the cursor pointer to the
next element.
3 public void remove() It removes the last elements returned by the iterator. It is
less used.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.
1. Iterator<T> iterator()
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the foundation on which the
collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean
addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of
Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have
duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion
order and is non-synchronized. The elements stored in the ArrayList class can be
randomly accessed. Consider the following example.
1. import java.util.*;
2. class TestJavaCollection1{
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
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally
to store the elements. It can store the duplicate elements. It maintains the insertion
order and is not synchronized. In LinkedList, the manipulation is fast because no
shifting is required.
1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ravi
Ajay
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of
Collection framework.
1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ayush
Amit
Ashish
Garima
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure,
i.e., Stack. The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o), which defines
its properties.
1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered
list that is used to hold the elements which are about to be processed. There are
various classes like PriorityQueue, Deque, and ArrayDeque which implements the
Queue interface.
There are various classes that implement the Queue interface, some of them are
given below.
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue.
1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables
us to perform the operations at both the ends.
1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }
Output:
Gautam
Karan
Ajay
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface.
It represents the unordered set of elements which doesn't allow us to store the
duplicate items. We can store at most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet.
1. import java.util.*;
2. public class TestJavaCollection7{
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:
Vijay
Ravi
Ajay
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It
extends the HashSet class and implements Set interface. Like HashSet, It also
contains unique elements. It maintains the insertion order and permits null elements.
1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ajay
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its
elements. The elements of the SortedSet are arranged in the increasing (ascending)
order. The SortedSet provides the additional methods that inhibit the natural
ordering of the elements.
1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<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
Ravi
Vijay
Java ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array,
but there is no size limit. We can add or remove elements anytime. So, it is much
more flexible than the traditional array. It is found in the java.util package. It is like
the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List
interface so we can use all the methods of the List interface here. The ArrayList
maintains the insertion order internally.
Constructors of ArrayList
Constructor Description
ArrayList(Collection<? extends E> c) It is used to build an array list that is initialized with the elements of t
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
Methods of ArrayList
Method Description
void add(int index, E element) It is used to insert the specified element at the specified positio
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> c) It is used to append all of the elements in the specified colle
this list, in the order that they are returned by the specified col
boolean addAll(int index, Collection<? It is used to append all the elements in the specified collec
extends E> c) specified position of the list.
void clear() It is used to remove all of the elements from this list.
E get(int index) It is used to fetch the element from the particular position of t
Iterator()
listIterator()
int lastIndexOf(Object o) It is used to return the index in this list of the last occurren
element, or -1 if the list does not contain this element.
boolean contains(Object o) It returns true if the list contains the specified element.
int indexOf(Object o) It is used to return the index in this list of the first occurren
element, or -1 if the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified posit
boolean remove(Object o) It is used to remove the first occurrence of the specified eleme
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E> It is used to remove all the elements from the list that
filter) predicate.
protected void removeRange(int fromIndex, It is used to remove all the elements lies within the given rang
int toIndex)
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the spec
operator)
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are pres
collection.
E set(int index, E element) It is used to replace the specified element in the list, prese
position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of the spe
int size() It is used to return the number of elements present in the list.
Java new generic collection allows you to have only one type of object in a collection.
Now it is type-safe, so typecasting is not required at runtime.
In a generic collection, we specify the type in angular braces. Now ArrayList is forced
to have the only specified type of object in it. If you try to add another type of object,
it gives a compile-time error.
For more information on Java generics, click here Java Generics Tutorial.
1. import java.util.*;
2. public class ArrayListExample1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Mango");//Adding object in arraylist
6. list.add("Apple");
7. list.add("Banana");
8. list.add("Grapes");
9. //Printing the arraylist object
10. System.out.println(list);
11. }
12. }
Output:
FileName: ArrayListExample2.java
1. import java.util.*;
2. public class ArrayListExample2{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Mango");//Adding object in arraylist
6. list.add("Apple");
7. list.add("Banana");
8. list.add("Grapes");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();//getting the Iterator
11. while(itr.hasNext()){//check if iterator has the elements
12. System.out.println(itr.next());//printing the element and move to next
13. }
14. }
15. }
Output:
Mango
Apple
Banana
Grapes
1. import java.util.*;
2. public class ArrayListExample3{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Mango");//Adding object in arraylist
6. list.add("Apple");
7. list.add("Banana");
8. list.add("Grapes");
9. //Traversing list through for-each loop
10. for(String fruit:list)
11. System.out.println(fruit);
12.
13. }
14. }
Output:
Mango
Apple
Banana
Grapes
FileName: ArrayListExample4.java
1. import java.util.*;
2. public class ArrayListExample4{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Mango");
6. al.add("Apple");
7. al.add("Banana");
8. al.add("Grapes");
9. //accessing the element
10. System.out.println("Returning element: "+al.get(1));//it will return the 2nd element, b
ecause index starts from 0
11. //changing the element
12. al.set(1,"Dates");
13. //Traversing list
14. for(String fruit:al)
15. System.out.println(fruit);
16.
17. }
18. }
Output:
FileName: SortArrayList.java
1. import java.util.*;
2. class SortArrayList{
3. public static void main(String args[]){
4. //Creating a list of fruits
5. List<String> list1=new ArrayList<String>();
6. list1.add("Mango");
7. list1.add("Apple");
8. list1.add("Banana");
9. list1.add("Grapes");
10. //Sorting the list
11. Collections.sort(list1);
12. //Traversing list through the for-each loop
13. for(String fruit:list1)
14. System.out.println(fruit);
15.
16. System.out.println("Sorting numbers...");
17. //Creating a list of numbers
18. List<Integer> list2=new ArrayList<Integer>();
19. list2.add(21);
20. list2.add(11);
21. list2.add(51);
22. list2.add(1);
23. //Sorting the list
24. Collections.sort(list2);
25. //Traversing list through the for-each loop
26. for(Integer number:list2)
27. System.out.println(number);
28. }
29.
30. }
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
1. By Iterator interface.
2. By for-each loop.
3. By ListIterator interface.
4. By for loop.
5. By forEach() method.
6. By forEachRemaining() method.
1. import java.util.*;
2. class ArrayList4{
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.
10. System.out.println("Traversing list through List Iterator:");
11. //Here, element iterates in reverse order
12. ListIterator<String> list1=list.listIterator(list.size());
13. while(list1.hasPrevious())
14. {
15. String str=list1.previous();
16. System.out.println(str);
17. }
18. System.out.println("Traversing list through for loop:");
19. for(int i=0;i<list.size();i++)
20. {
21. System.out.println(list.get(i));
22. }
23.
24. System.out.println("Traversing list through forEach() method:");
25. //The forEach() method is a new feature, introduced in Java 8.
26. list.forEach(a->{ //Here, we are using lambda expression
27. System.out.println(a);
28. });
29.
30. System.out.println("Traversing list through forEachRemaining() method:");
31. Iterator<String> itr=list.iterator();
32. itr.forEachRemaining(a-> //Here, we are using lambda expression
33. {
34. System.out.println(a);
35. });
36. }
37. }
Output:
FileName: ArrayList5.java
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
1. import java.util.*;
2. class ArrayList5{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8. //creating arraylist
9. ArrayList<Student> al=new ArrayList<Student>();
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13. //Getting Iterator
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20. }
21. }
Output:
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
FileName: ArrayList6.java
1. import java.io.*;
2. import java.util.*;
3. class ArrayList6 {
4.
5. public static void main(String [] args)
6. {
7. ArrayList<String> al=new ArrayList<String>();
8. al.add("Ravi");
9. al.add("Vijay");
10. al.add("Ajay");
11.
12. try
13. {
14. //Serialization
15. FileOutputStream fos=new FileOutputStream("file");
16. ObjectOutputStream oos=new ObjectOutputStream(fos);
17. oos.writeObject(al);
18. fos.close();
19. oos.close();
20. //Deserialization
21. FileInputStream fis=new FileInputStream("file");
22. ObjectInputStream ois=new ObjectInputStream(fis);
23. ArrayList list=(ArrayList)ois.readObject();
24. System.out.println(list);
25. }catch(Exception e)
26. {
27. System.out.println(e);
28. }
29. }
30. }
Output:
FileName: ArrayList7.java
1. import java.util.*;
2. class ArrayList7{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. System.out.println("Initial list of elements: "+al);
6. //Adding elements to the end of the list
7. al.add("Ravi");
8. al.add("Vijay");
9. al.add("Ajay");
10. System.out.println("After invoking add(E e) method: "+al);
11. //Adding an element at the specific position
12. al.add(1, "Gaurav");
13. System.out.println("After invoking add(int index, E element) method: "+
al);
14. ArrayList<String> al2=new ArrayList<String>();
15. al2.add("Sonoo");
16. al2.add("Hanumat");
17. //Adding second list elements to the first list
18. al.addAll(al2);
19. System.out.println("After invoking addAll(Collection<? extends E> c) m
ethod: "+al);
20. ArrayList<String> al3=new ArrayList<String>();
21. al3.add("John");
22. al3.add("Rahul");
23. //Adding second list elements to the first list at specific position
24. al.addAll(1, al3);
25. System.out.println("After invoking addAll(int index, Collection<? extend
s E> c) method: "+al);
26.
27. }
28. }
Output:
FileName: ArrayList8.java
1. import java.util.*;
2. class ArrayList8 {
3.
4. public static void main(String [] args)
5. {
6. ArrayList<String> al=new ArrayList<String>();
7. al.add("Ravi");
8. al.add("Vijay");
9. al.add("Ajay");
10. al.add("Anuj");
11. al.add("Gaurav");
12. System.out.println("An initial list of elements: "+al);
13. //Removing specific element from arraylist
14. al.remove("Vijay");
15. System.out.println("After invoking remove(object) method: "+al);
16. //Removing element on the basis of specific position
17. al.remove(0);
18. System.out.println("After invoking remove(index) method: "+al);
19.
20. //Creating another arraylist
21. ArrayList<String> al2=new ArrayList<String>();
22. al2.add("Ravi");
23. al2.add("Hanumat");
24. //Adding new elements to arraylist
25. al.addAll(al2);
26. System.out.println("Updated list : "+al);
27. //Removing all the new elements from arraylist
28. al.removeAll(al2);
29. System.out.println("After invoking removeAll() method: "+al);
30. //Removing elements on the basis of specified condition
31. al.removeIf(str -
> str.contains("Ajay")); //Here, we are using Lambda expression
32. System.out.println("After invoking removeIf() method: "+al);
33. //Removing all the elements available in the list
34. al.clear();
35. System.out.println("After invoking clear() method: "+al);
36. }
37. }
Output:
1. import java.util.*;
2. class ArrayList9{
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.retainAll(al2);
12. System.out.println("iterating the elements after retaining the elements of al2");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17. }
18. }
Output:
Output:
FileName: ArrayListExample20.java
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ArrayListExample20 {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc
Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantit
y);
29. }
30. }
31. }
Output:
FileName: SizeCapacity.java
1. import java.util.*;
2.
3. public class SizeCapacity
4. {
5.
6. public static void main(String[] args) throws Exception
7. {
8.
9. ArrayList<Integer> al = new ArrayList<Integer>();
10.
11. System.out.println("The size of the array is: " + al.size());
12. }
13. }
Output:
Explanation: The output makes sense as we have not done anything with the array
list. Now observe the following program.
FileName: SizeCapacity1.java
1. import java.util.*;
2.
3. public class SizeCapacity1
4. {
5.
6. public static void main(String[] args) throws Exception
7. {
8.
9. ArrayList<Integer> al = new ArrayList<Integer>(10);
10.
11. System.out.println("The size of the array is: " + al.size());
12. }
13. }
Output:
Constructor Description
Method Description
void add(int index, E element) It is used to insert the specified element at the
specified position index in a list.
<T> T[] toArray(T[] a) It returns an array containing all the elements in the
proper sequence (from first to the last element); the
runtime type of the returned array is that of the
specified array.
1. import java.util.*;
2. public class LinkedList1{
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
1. import java.util.*;
2. public class LinkedList2{
3. public static void main(String args[]){
4. LinkedList<String> ll=new LinkedList<String>();
5. System.out.println("Initial list of elements: "+ll);
6. ll.add("Ravi");
7. ll.add("Vijay");
8. ll.add("Ajay");
9. System.out.println("After invoking add(E e) method: "+ll);
10. //Adding an element at the specific position
11. ll.add(1, "Gaurav");
12. System.out.println("After invoking add(int index, E element) method: "+
ll);
13. LinkedList<String> ll2=new LinkedList<String>();
14. ll2.add("Sonoo");
15. ll2.add("Hanumat");
16. //Adding second list elements to the first list
17. ll.addAll(ll2);
18. System.out.println("After invoking addAll(Collection<? extends E> c) m
ethod: "+ll);
19. LinkedList<String> ll3=new LinkedList<String>();
20. ll3.add("John");
21. ll3.add("Rahul");
22. //Adding second list elements to the first list at specific position
23. ll.addAll(1, ll3);
24. System.out.println("After invoking addAll(int index, Collection<? extend
s E> c) method: "+ll);
25. //Adding an element at the first position
26. ll.addFirst("Lokesh");
27. System.out.println("After invoking addFirst(E e) method: "+ll);
28. //Adding an element at the last position
29. ll.addLast("Harsh");
30. System.out.println("After invoking addLast(E e) method: "+ll);
31.
32. }
33. }
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay,
Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]
1. import java.util.*;
2. public class LinkedList3 {
3.
4. public static void main(String [] args)
5. {
6. LinkedList<String> ll=new LinkedList<String>();
7. ll.add("Ravi");
8. ll.add("Vijay");
9. ll.add("Ajay");
10. ll.add("Anuj");
11. ll.add("Gaurav");
12. ll.add("Harsh");
13. ll.add("Virat");
14. ll.add("Gaurav");
15. ll.add("Harsh");
16. ll.add("Amit");
17. System.out.println("Initial list of elements: "+ll);
18. //Removing specific element from arraylist
19. ll.remove("Vijay");
20. System.out.println("After invoking remove(object) method: "+ll);
21. //Removing element on the basis of specific position
22. ll.remove(0);
23. System.out.println("After invoking remove(index) method: "+ll);
24. LinkedList<String> ll2=new LinkedList<String>();
25. ll2.add("Ravi");
26. ll2.add("Hanumat");
27. // Adding new elements to arraylist
28. ll.addAll(ll2);
29. System.out.println("Updated list : "+ll);
30. //Removing all the new elements from arraylist
31. ll.removeAll(ll2);
32. System.out.println("After invoking removeAll() method: "+ll);
33. //Removing first element from the list
34. ll.removeFirst();
35. System.out.println("After invoking removeFirst() method: "+ll);
36. //Removing first element from the list
37. ll.removeLast();
38. System.out.println("After invoking removeLast() method: "+ll);
39. //Removing first occurrence of element from the list
40. ll.removeFirstOccurrence("Gaurav");
41. System.out.println("After invoking removeFirstOccurrence() method: "
+ll);
42. //Removing last occurrence of element from the list
43. ll.removeLastOccurrence("Harsh");
44. System.out.println("After invoking removeLastOccurrence() method: "
+ll);
45.
46. //Removing all the elements available in the list
47. ll.clear();
48. System.out.println("After invoking clear() method: "+ll);
49. }
50. }
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh,
Virat, Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit,
Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav,
Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []
1. import java.util.*;
2. public class LinkedList4{
3. public static void main(String args[]){
4.
5. LinkedList<String> ll=new LinkedList<String>();
6. ll.add("Ravi");
7. ll.add("Vijay");
8. ll.add("Ajay");
9. //Traversing the list of elements in reverse order
10. Iterator i=ll.descendingIterator();
11. while(i.hasNext())
12. {
13. System.out.println(i.next());
14. }
15.
16. }
17. }
Output: Ajay
Vijay
Ravi
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class LinkedListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new LinkedList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan",
"Mc Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qu
antity);
29. }
30. }
31. }
Output:
ArrayList LinkedList
1) ArrayList internally uses a dynamic array to LinkedList internally uses a doubly linked
store the elements. list to store the elements.
2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses an array. If any element is ArrayList because it uses a doubly linked list,
removed from the array, all the other elements so no bit shifting is required in memory.
are shifted in memory.
3) An ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List and
Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
5) The memory location for the elements of an The location for the elements of a linked list
ArrayList is contiguous. is not contagious.
7) To be precise, an ArrayList is a resizable array. LinkedList implements the doubly linked list
of the list interface.
FileName: TestArrayLinked.java
1. import java.util.*;
2. class TestArrayLinked{
3. public static void main(String args[]){
4.
5. List<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Ravi");//adding object in arraylist
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10.
11. List<String> al2=new LinkedList<String>();//creating linkedlist
12. al2.add("James");//adding object in linkedlist
13. al2.add("Serena");
14. al2.add("Swati");
15. al2.add("Junaid");
16.
17. System.out.println("arraylist: "+al);
18. System.out.println("linkedlist: "+al2);
19. }
20. }
Output:
arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]
Java List
List in Java provides the facility to maintain the ordered collection. It contains the
index-based methods to insert, update, delete and search the elements. It can have
the duplicate elements also. We can also store the null elements in the list.
The List interface is found in the java.util package and inherits the Collection
interface. It is a factory of ListIterator interface. Through the ListIterator, we can
iterate the list in forward and backward directions. The implementation classes of List
interface are ArrayList, LinkedList, Stack and Vector. The ArrayList and LinkedList are
widely used in Java programming. The Vector class is deprecated since Java 5.
Method Description
void add(int index, E element) It is used to insert the specified element at the
specified position in a list.
boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
int hashcode() It is used to return the hash code value for a list.
int lastIndexOf(Object o) It is used to return the index in this list of the last
occurrence of the specified element, or -1 if the list
does not contain this element.
boolean contains(Object o) It returns true if the list contains the specified element
boolean containsAll(Collection<?> c) It returns true if the list contains all the specified
element
int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List
does not contain this element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with
operator) the specified element.
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are
present in the specified collection.
E set(int index, E element) It is used to replace the specified element in the list,
present at the specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis
of specified comparator.
In short, you can create the List of any type. The ArrayList<T> and LinkedList<T>
classes are used to specify the type. Here, T denotes the type.
1. import java.util.*;
2. public class ListExample1{
3. public static void main(String args[]){
4. //Creating a List
5. List<String> list=new ArrayList<String>();
6. //Adding elements in the List
7. list.add("Mango");
8. list.add("Apple");
9. list.add("Banana");
10. list.add("Grapes");
11. //Iterating the List element using for-each loop
12. for(String fruit:list)
13. System.out.println(fruit);
14.
15. }
16. }
Output:
Mango
Apple
Banana
Grapes
1. import java.util.*;
2. public class ArrayToListExample{
3. public static void main(String args[]){
4. //Creating Array
5. String[] array={"Java","Python","PHP","C++"};
6. System.out.println("Printing Array: "+Arrays.toString(array));
7. //Converting Array to List
8. List<String> list=new ArrayList<String>();
9. for(String lang:array){
10. list.add(lang);
11. }
12. System.out.println("Printing List: "+list);
13.
14. }
15. }
Output:
1. import java.util.*;
2. public class ListToArrayExample{
3. public static void main(String args[]){
4. List<String> fruitList = new ArrayList<>();
5. fruitList.add("Mango");
6. fruitList.add("Banana");
7. fruitList.add("Apple");
8. fruitList.add("Strawberry");
9. //Converting ArrayList to Array
10. String[] array = fruitList.toArray(new String[fruitList.size()]);
11. System.out.println("Printing Array: "+Arrays.toString(array));
12. System.out.println("Printing List: "+fruitList);
13. }
14. }
Output:
1. import java.util.*;
2. public class ListExample2{
3. public static void main(String args[]){
4. //Creating a List
5. List<String> list=new ArrayList<String>();
6. //Adding elements in the List
7. list.add("Mango");
8. list.add("Apple");
9. list.add("Banana");
10. list.add("Grapes");
11. //accessing the element
12. System.out.println("Returning element: "+list.get(1));//it will return the 2nd element,
because index starts from 0
13. //changing the element
14. list.set(1,"Dates");
15. //Iterating the List element using for-each loop
16. for(String fruit:list)
17. System.out.println(fruit);
18.
19. }
20. }
Output:
1. import java.util.*;
2. class SortArrayList{
3. public static void main(String args[]){
4. //Creating a list of fruits
5. List<String> list1=new ArrayList<String>();
6. list1.add("Mango");
7. list1.add("Apple");
8. list1.add("Banana");
9. list1.add("Grapes");
10. //Sorting the list
11. Collections.sort(list1);
12. //Traversing list through the for-each loop
13. for(String fruit:list1)
14. System.out.println(fruit);
15.
16. System.out.println("Sorting numbers...");
17. //Creating a list of numbers
18. List<Integer> list2=new ArrayList<Integer>();
19. list2.add(21);
20. list2.add(11);
21. list2.add(51);
22. list2.add(1);
23. //Sorting the list
24. Collections.sort(list2);
25. //Traversing list through the for-each loop
26. for(Integer number:list2)
27. System.out.println(number);
28. }
29.
30. }
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
Method Description
void add(E e) This method inserts the specified element into the list.
boolean hasNext() This method returns true if the list iterator has more elements while
traversing the list in the forward direction.
E next() This method returns the next element in the list and advances the cursor
position.
int nextIndex() This method returns the index of the element that would be returned by a
subsequent call to next()
boolean This method returns true if this list iterator has more elements while
hasPrevious() traversing the list in the reverse direction.
E previous() This method returns the previous element in the list and moves the cursor
position backward.
E previousIndex() This method returns the index of the element that would be returned by a
subsequent call to previous().
void remove() This method removes the last element from the list that was returned by
next() or previous() methods
void set(E e) This method replaces the last element returned by next() or previous()
methods with the specified element.
Output:
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ListExample5 {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc
Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }
Output:
In this section, we will discuss the Java Stack class, its methods, and implement the
stack data structure in a Java program. But before moving to the Java Stack class
have a quick view of how the stack works.
The stack data structure has the two most important operations that
are push and pop. The push operation inserts an element into the stack and pop
operation removes an element from the top of the stack. Let's see how they work on
stack.
Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.
Empty Stack: If the stack has no element is known as an empty stack. When the
stack is empty the value of the top variable is -1.
When we push an element into the stack the top is increased by 1. In the following
figure,
ADVERTISEMENT
Stack Class Constructor
The Stack class contains only the default constructor that creates an empty stack.
1. public Stack()
Creating a Stack
If we want to create a stack, first, import the java.util package and create an object of
the Stack class.
Or
Where type denotes the type of stack like Integer, String, etc.
push(E item) E The method pushes (insert) an element onto the top of
the stack.
Syntax
Returns: The method returns true if the stack is empty, else returns false.
In the following example, we have created an instance of the Stack class. After that,
we have invoked the empty() method two times. The first time it
returns true because we have not pushed any element into the stack. After that, we
have pushed elements into the stack. Again we have invoked the empty() method
that returns false because the stack is not empty.
StackEmptyMethodExample.java
1. import java.util.Stack;
2. public class StackEmptyMethodExample
3. {
4. public static void main(String[] args)
5. {
6. //creating an instance of Stack class
7. Stack<Integer> stk= new Stack<>();
8. // checking stack is empty or not
9. boolean result = stk.empty();
10. System.out.println("Is the stack empty? " + result);
11. // pushing elements into stack
12. stk.push(78);
13. stk.push(113);
14. stk.push(90);
15. stk.push(120);
16. //prints elements of the stack
17. System.out.println("Elements in Stack: " + stk);
18. result = stk.empty();
19. System.out.println("Is the stack empty? " + result);
20. }
21. }
Output:
Syntax
Returns: The method returns the argument that we have passed as a parameter.
Syntax
1. public E pop()
Let's implement the stack in a Java program and perform push and pop operations.
StackPushPopExample.java
1. import java.util.*;
2. public class StackPushPopExample
3. {
4. public static void main(String args[])
5. {
6. //creating an object of Stack class
7. Stack <Integer> stk = new Stack<>();
8. System.out.println("stack: " + stk);
9. //pushing elements into the stack
10. pushelmnt(stk, 20);
11. pushelmnt(stk, 13);
12. pushelmnt(stk, 89);
13. pushelmnt(stk, 90);
14. pushelmnt(stk, 11);
15. pushelmnt(stk, 45);
16. pushelmnt(stk, 18);
17. //popping elements from the stack
18. popelmnt(stk);
19. popelmnt(stk);
20. //throws exception if the stack is empty
21. try
22. {
23. popelmnt(stk);
24. }
25. catch (EmptyStackException e)
26. {
27. System.out.println("empty stack");
28. }
29. }
30. //performing push operation
31. static void pushelmnt(Stack stk, int x)
32. {
33. //invoking push() method
34. stk.push(new Integer(x));
35. System.out.println("push -> " + x);
36. //prints modified stack
37. System.out.println("stack: " + stk);
38. }
39. //performing pop operation
40. static void popelmnt(Stack stk)
41. {
42. System.out.print("pop -> ");
43. //invoking pop() method
44. Integer x = (Integer) stk.pop();
45. System.out.println(x);
46. //prints modified stack
47. System.out.println("stack: " + stk);
48. }
49. }
Output:
stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11
stack: [20, 13, 89, 90, 11]
push -> 45
stack: [20, 13, 89, 90, 11, 45]
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
stack: [20, 13, 89, 90, 11, 45]
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]
Syntax
1. public E peek()
StackPeekMethodExample.java
1. import java.util.Stack;
2. public class StackPeekMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. // pushing elements into Stack
8. stk.push("Apple");
9. stk.push("Grapes");
10. stk.push("Mango");
11. stk.push("Orange");
12. System.out.println("Stack: " + stk);
13. // Access element from the top of the stack
14. String fruits = stk.peek();
15. //prints stack
16. System.out.println("Element at top: " + fruits);
17. }
18. }
Output:
Suppose, o is an object in the stack that we want to search for. The method returns
the distance from the top of the stack of the occurrence nearest the top of the stack.
It uses equals() method to search an object in the stack.
Syntax
StackSearchMethodExample.java
1. import java.util.Stack;
2. public class StackSearchMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. //pushing elements into Stack
8. stk.push("Mac Book");
9. stk.push("HP");
10. stk.push("DELL");
11. stk.push("Asus");
12. System.out.println("Stack: " + stk);
13. // Search an element
14. int location = stk.search("HP");
15. System.out.println("Location of Dell: " + location);
16. }
17. }
Java Stack Operations
Size of the Stack
We can also find the size of the stack using the size() method of the Vector class. It
returns the total number of elements (size of the stack) in the stack.
Syntax
StackSizeExample.java
1. import java.util.Stack;
2. public class StackSizeExample
3. {
4. public static void main (String[] args)
5. {
6. Stack stk = new Stack();
7. stk.push(22);
8. stk.push(33);
9. stk.push(44);
10. stk.push(55);
11. stk.push(66);
12. // Checks the Stack is empty or not
13. boolean rslt=stk.empty();
14. System.out.println("Is the stack empty or not? " +rslt);
15. // Find the size of the Stack
16. int x=stk.size();
17. System.out.println("The stack size is: "+x);
18. }
19. }
Output:
Iterate Elements
Iterate means to fetch the elements of the stack. We can fetch elements of the stack
using three different methods are as follows:
It is the method of the Iterator interface. It returns an iterator over the elements in
the stack. Before using the iterator() method import the java.util.Iterator package.
Syntax
1. Iterator<T> iterator()
Let's perform an iteration over the stack.
StackIterationExample1.java
1. import java.util.Iterator;
2. import java.util.Stack;
3. public class StackIterationExample1
4. {
5. public static void main (String[] args)
6. {
7. //creating an object of Stack class
8. Stack stk = new Stack();
9. //pushing elements into stack
10. stk.push("BMW");
11. stk.push("Audi");
12. stk.push("Ferrari");
13. stk.push("Bugatti");
14. stk.push("Jaguar");
15. //iteration over the stack
16. Iterator iterator = stk.iterator();
17. while(iterator.hasNext())
18. {
19. Object values = iterator.next();
20. System.out.println(values);
21. }
22. }
23. }
Output:
BMW
Audi
Ferrari
Bugatti
Jaguar
Java provides a forEach() method to iterate over the elements. The method is defined
in the Iterable and Stream interface.
Syntax
1. default void forEach(Consumer<super T>action)
StackIterationExample2.java
1. import java.util.*;
2. public class StackIterationExample2
3. {
4. public static void main (String[] args)
5. {
6. //creating an instance of Stack class
7. Stack <Integer> stk = new Stack<>();
8. //pushing elements into stack
9. stk.push(119);
10. stk.push(203);
11. stk.push(988);
12. System.out.println("Iteration over the stack using forEach() Method:");
13. //invoking forEach() method for iteration over the stack
14. stk.forEach(n ->
15. {
16. System.out.println(n);
17. });
18. }
19. }
Output:
This method returns a list iterator over the elements in the mentioned list (in
sequence), starting at the specified position in the list. It iterates the stack from top
to bottom.
Syntax
Returns: This method returns a list iterator over the elements, in sequence.
StackIterationExample3.java
1. import java.util.Iterator;
2. import java.util.ListIterator;
3. import java.util.Stack;
4.
5. public class StackIterationExample3
6. {
7. public static void main (String[] args)
8. {
9. Stack <Integer> stk = new Stack<>();
10. stk.push(119);
11. stk.push(203);
12. stk.push(988);
13. ListIterator<Integer> ListIterator = stk.listIterator(stk.size());
14. System.out.println("Iteration over the Stack from top to bottom:");
15. while (ListIterator.hasPrevious())
16. {
17. Integer avg = ListIterator.previous();
18. System.out.println(avg);
19. }
20. }
21. }
Output:
Being an interface, the queue requires, for the declaration, a concrete class, and the
most common classes are the LinkedList and PriorityQueue in Java. Implementations
done by these classes are not thread safe. If it is required to have a thread safe
implementation, PriorityBlockingQueue is an available option.
Method Description
boolean It is used to insert the specified element into this queue and return true
add(object) upon success.
Object remove() It is used to retrieves and removes the head of this queue.
Object poll() It is used to retrieves and removes the head of this queue, or returns
null if this queue is empty.
Object element() It is used to retrieves, but does not remove, the head of this queue.
Object peek() It is used to retrieves, but does not remove, the head of this queue, or
returns null if this queue is empty.
Features of a Queue
The following are some important features of a queue.
o As discussed earlier, FIFO concept is used for insertion and deletion of elements from
a queue.
o The Java Queue provides support for all of the methods of the Collection interface
including deletion, insertion, etc.
o PriorityQueue, ArrayBlockingQueue and LinkedList are the implementations that are
used most frequently.
o The NullPointerException is raised, if any null operation is done on the
BlockingQueues.
o Those Queues that are present in the util package are known as Unbounded Queues.
o Those Queues that are present in the util.concurrent package are known as bounded
Queues.
o All Queues barring the Deques facilitates removal and insertion at the head and tail
of the queue; respectively. In fact, deques support element insertion and removal at
both ends.
PriorityQueue Class
PriorityQueue is also class that is defined in the collection framework that gives us a
way for processing the objects on the basis of priority. It is already described that the
insertion and deletion of objects follows FIFO pattern in the Java queue. However,
sometimes the elements of the queue are needed to be processed according to the
priority, that's where a PriorityQueue comes into action.
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:
head:Amit
head:Amit
iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
after removing two elements:
Karan
Rahul
Vijay
FileName: LinkedListExample.java
1. import java.util.*;
2. class Book implements Comparable<Book>{
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. public int compareTo(Book b) {
14. if(id>b.id){
15. return 1;
16. }else if(id<b.id){
17. return -1;
18. }else{
19. return 0;
20. }
21. }
22. }
23. public class LinkedListExample {
24. public static void main(String[] args) {
25. Queue<Book> queue=new PriorityQueue<Book>();
26. //Creating Books
27. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
28. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
29. Book b3=new Book(101,"Data Communications & Networking","Forouzan",
"Mc Graw Hill",4);
30. //Adding Books to the queue
31. queue.add(b1);
32. queue.add(b2);
33. queue.add(b3);
34. System.out.println("Traversing the queue elements:");
35. //Traversing queue elements
36. for(Book b:queue){
37. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qu
antity);
38. }
39. queue.remove();
40. System.out.println("After removing one book record:");
41. for(Book b:queue){
42. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantit
y);
43. }
44. }
45. }
Output:
Java HashSet
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.
ADVERTISEMENT
ADVERTISEMENT
2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer
capacity grows automatically as elements are added to the HashSet.
3) HashSet(int capacity, float It is used to initialize the capacity of the hash set to the given intege
loadFactor) the specified load factor.
4) HashSet(Collection<? extends It is used to initialize the hash set by using the elements of the collect
E> c)
1. import java.util.*;
2. class HashSet1{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet();
6. set.add("One");
7. set.add("Two");
8. set.add("Three");
9. set.add("Four");
10. set.add("Five");
11. Iterator<String> i=set.iterator();
12. while(i.hasNext())
13. {
14. System.out.println(i.next());
15. }
16. }
17. }
Five
One
Four
Two
Three
1. import java.util.*;
2. class HashSet2{
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. }
Ajay
Vijay
Ravi
1. import java.util.*;
2. class HashSet3{
3. public static void main(String args[]){
4. HashSet<String> set=new HashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Arun");
8. set.add("Sumit");
9. System.out.println("An initial list of elements: "+set);
10. //Removing specific element from HashSet
11. set.remove("Ravi");
12. System.out.println("After invoking remove(object) method: "+set);
13. HashSet<String> set1=new HashSet<String>();
14. set1.add("Ajay");
15. set1.add("Gaurav");
16. set.addAll(set1);
17. System.out.println("Updated List: "+set);
18. //Removing all the new elements from HashSet
19. set.removeAll(set1);
20. System.out.println("After invoking removeAll() method: "+set);
21. //Removing elements on the basis of specified condition
22. set.removeIf(str->str.contains("Vijay"));
23. System.out.println("After invoking removeIf() method: "+set);
24. //Removing all the elements available in the set
25. set.clear();
26. System.out.println("After invoking clear() method: "+set);
27. }
28. }
An initial list of elements: [Vijay, Ravi, Arun, Sumit]
After invoking remove(object) method: [Vijay, Arun, Sumit]
Updated List: [Vijay, Arun, Gaurav, Sumit, Ajay]
After invoking removeAll() method: [Vijay, Arun, Sumit]
After invoking removeIf() method: [Arun, Sumit]
After invoking clear() method: []
1. import java.util.*;
2. class HashSet4{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();
5. list.add("Ravi");
6. list.add("Vijay");
7. list.add("Ajay");
8.
9. HashSet<String> set=new HashSet(list);
10. set.add("Gaurav");
11. Iterator<String> i=set.iterator();
12. while(i.hasNext())
13. {
14. System.out.println(i.next());
15. }
16. }
17. }
Vijay
Ravi
Gaurav
Ajay
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class HashSetExample {
15. public static void main(String[] args) {
16. HashSet<Book> set=new HashSet<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan",
"Mc Graw Hill",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to HashSet
22. set.add(b1);
23. set.add(b2);
24. set.add(b3);
25. //Traversing HashSet
26. for(Book b:set){
27. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qu
antity);
28. }
29. }
30. }
Output:
Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set
interface. It inherits the HashSet class and implements the Set interface.
ADVERTISEMENT
o Java LinkedHashSet class contains unique elements only like HashSet.
o Java LinkedHashSet class provides all optional set operations and permits null
elements.
o Java LinkedHashSet class is non-synchronized.
o Java LinkedHashSet class maintains insertion order.
Note: Keeping the insertion order in the LinkedHashset has some additional costs, both
in terms of extra memory and extra CPU cycles. Therefore, if it is not required to
maintain the insertion order, go for the lighter-weight HashMap or the HashSet instead.
Constructor Description
HashSet(Collection c) It is used to initialize the hash set by using the elements of the
collection c.
LinkedHashSet(int capacity) It is used to initialize the capacity of the linked hash set to the
given integer value capacity.
LinkedHashSet(int capacity, It is used to initialize both the capacity and the fill ratio (also
float fillRatio) called load capacity) of the hash set from its argument.
Java LinkedHashSet Example
Let's see a simple example of the Java LinkedHashSet class. Here you can notice that
the elements iterate in insertion order.
FileName: LinkedHashSet1.java
1. import java.util.*;
2. class LinkedHashSet1{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. LinkedHashSet<String> set=new LinkedHashSet();
6. set.add("One");
7. set.add("Two");
8. set.add("Three");
9. set.add("Four");
10. set.add("Five");
11. Iterator<String> i=set.iterator();
12. while(i.hasNext())
13. {
14. System.out.println(i.next());
15. }
16. }
17. }
Output:
One
Two
Three
Four
Five
Note: We can also use the enhanced for loop for displaying the elements.
1. import java.util.*;
2. class LinkedHashSet2{
3. public static void main(String args[]){
4. LinkedHashSet<String> al=new LinkedHashSet<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ajay
1. import java.util.*;
2.
3. public class LinkedHashSet3
4. {
5.
6. // main method
7. public static void main(String argvs[])
8. {
9.
10. // Creating an empty LinekdhashSet of string type
11. LinkedHashSet<String> lhs = new LinkedHashSet<String>();
12.
13. // Adding elements to the above Set
14. // by invoking the add() method
15. lhs.add("Java");
16. lhs.add("T");
17. lhs.add("Point");
18. lhs.add("Good");
19. lhs.add("Website");
20.
21. // displaying all the elements on the console
22. System.out.println("The hash set is: " + lhs);
23.
24. // Removing an element from the above linked Set
25.
26. // since the element "Good" is present, therefore, the method remove()
27. // returns true
28. System.out.println(lhs.remove("Good"));
29.
30. // After removing the element
31. System.out.println("After removing the element, the hash set is: " + lhs);
32.
33. // since the element "For" is not present, therefore, the method remove()
34. // returns false
35. System.out.println(lhs.remove("For"));
36.
37. }
38. }
Output:
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class LinkedHashSetExample {
15. public static void main(String[] args) {
16. LinkedHashSet<Book> hs=new LinkedHashSet<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan",
"Mc Graw Hill",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to hash table
22. hs.add(b1);
23. hs.add(b2);
24. hs.add(b3);
25. //Traversing hash table
26. for(Book b:hs){
27. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.qu
antity);
28. }
29. }
30. }
Output:
A Map is useful if you have to search, update or delete elements on the basis of a
key.
Java Map Hierarchy
There are two interfaces for implementing Map in java: Map and SortedMap, and
three classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is
given below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key
or value.
Method Description
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified
key in the map only if it is not already specified.
boolean remove(Object key, Object It removes the specified values with the
value) associated specified keys from the map.
Set keySet() It returns the Set view containing all the keys.
Set<Map.Entry<K,V>> entrySet() It returns the Set view containing all the keys and
values.
V computeIfAbsent(K key, Function<? It is used to compute its value using the given
super K,? extends V> mapping function, if the specified key is not
mappingFunction) already associated with a value (or is mapped to
null), and enters it into this map unless null.
boolean containsValue(Object value) This method returns true if some value equal to
the value exists within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to
the key exists within the map, else return false.
void forEach(BiConsumer<? super K,? It performs the given action for each entry in the
super V> action) map until all entries have been processed or the
action throws an exception.
V get(Object key) This method returns the object that contains the
value associated with the key.
int hashCode() It returns the hash code value for the Map
boolean isEmpty() This method returns true if the map is empty;
returns false if it contains at least one key.
V merge(K key, V value, BiFunction<? If the specified key is not already associated with
super V,? super V,? extends V> a value or is associated with null, associates it
remappingFunction) with the given non-null value.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a
newValue) specified key.
void replaceAll(BiFunction<? super It replaces each entry's value with the result of
K,? super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function
throws an exception.
Map.Entry Interface
Entry is the subinterface of Map. So we will be accessed it by Map.Entry name. It
returns a collection-view of the map, whose elements are of this class. It provides
methods to get key and value.
Method Description
1. //Non-generic
2. import java.util.*;
3. public class MapExample1 {
4. public static void main(String[] args) {
5. Map map=new HashMap();
6. //Adding elements to map
7. map.put(1,"Amit");
8. map.put(5,"Rahul");
9. map.put(2,"Jai");
10. map.put(6,"Amit");
11. //Traversing Map
12. Set set=map.entrySet();//Converting to Set so that we can traverse
13. Iterator itr=set.iterator();
14. while(itr.hasNext()){
15. //Converting to Map.Entry so that we can get key and value separately
16. Map.Entry entry=(Map.Entry)itr.next();
17. System.out.println(entry.getKey()+" "+entry.getValue());
18. }
19. }
20. }
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
1. import java.util.*;
2. class MapExample2{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. //Elements can traverse in any order
9. for(Map.Entry m:map.entrySet()){
10. System.out.println(m.getKey()+" "+m.getValue());
11. }
12. }
13. }
Output:
102 Rahul
100 Amit
101 Vijay
Output:
100=Amit
101=Vijay
102=Rahul
1. import java.util.*;
2. class MapExample4{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. //Returns a Set view of the mappings contained in this map
9. map.entrySet()
10. //Returns a sequential Stream with this collection as its source
11. .stream()
12. //Sorted according to the provided Comparator
13. .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
14. //Performs an action for each element of this stream
15. .forEach(System.out::println);
16. }
17. }
Output:
102=Rahul
101=Vijay
100=Amit
1. import java.util.*;
2. class MapExample5{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. //Returns a Set view of the mappings contained in this map
9. map.entrySet()
10. //Returns a sequential Stream with this collection as its source
11. .stream()
12. //Sorted according to the provided Comparator
13. .sorted(Map.Entry.comparingByValue())
14. //Performs an action for each element of this stream
15. .forEach(System.out::println);
16. }
17. }
Output:
100=Amit
102=Rahul
101=Vijay
1. import java.util.*;
2. class MapExample6{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. //Returns a Set view of the mappings contained in this map
9. map.entrySet()
10. //Returns a sequential Stream with this collection as its source
11. .stream()
12. //Sorted according to the provided Comparator
13. .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
14. //Performs an action for each element of this stream
15. .forEach(System.out::println);
16. }
17. }
Output:
101=Vijay
102=Rahul
100=Amit
Java HashMap
Java HashMap class implements the Map interface which allows us to store key and
value pair, where keys should be unique. If you try to insert the duplicate key, it will
replace the element of the corresponding key. It is easy to perform operations using
the key index like updation, deletion, etc. HashMap class is found in
the java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It
allows us to store the null elements as well, but there should be only one null key.
Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and V for value.
It inherits the AbstractMap class and implements the Map interface.
Points to remember
Constructor Description
HashMap(int capacity, float It is used to initialize both the capacity and load factor of
loadFactor) the hash map by using its arguments.
Method Description
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key
in the map only if it is not already specified.
boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the map.
V compute(K key, BiFunction<? super It is used to compute a mapping for the specified
K,? super V,? extends V> key and its current mapped value (or null if there is
remappingFunction) no current mapping).
V computeIfAbsent(K key, Function<? It is used to compute its value using the given
super K,? extends V> mapping function, if the specified key is not
mappingFunction) already associated with a value (or is mapped to
null), and enters it into this map unless null.
boolean containsValue(Object value) This method returns true if some value equal to
the value exists within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the
key exists within the map, else return false.
void forEach(BiConsumer<? super K,? It performs the given action for each entry in the
super V> action) map until all entries have been processed or the
action throws an exception.
V get(Object key) This method returns the object that contains the
value associated with the key.
V getOrDefault(Object key, V It returns the value to which the specified key is
defaultValue) mapped, or defaultValue if the map contains no
mapping for the key.
V merge(K key, V value, BiFunction<? If the specified key is not already associated with a
super V,? super V,? extends V> value or is associated with null, associates it with
remappingFunction) the given non-null value.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a
newValue) specified key.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of
super V,? extends V> function) invoking the given function on that entry until all
entries have been processed or the function
throws an exception.
1. import java.util.*;
2. public class HashMapExample1{
3. public static void main(String args[]){
4. HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating Hash
Map
5. map.put(1,"Mango"); //Put elements in Map
6. map.put(2,"Apple");
7. map.put(3,"Banana");
8. map.put(4,"Grapes");
9.
10. System.out.println("Iterating Hashmap...");
11. for(Map.Entry m : map.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Iterating Hashmap...
1 Mango
2 Apple
3 Banana
4 Grapes
In this example, we are storing Integer as the key and String as the value, so we are
using HashMap<Integer,String> as the type. The put() method inserts the elements
in the map.
To get the key and value elements, we should call the getKey() and getValue()
methods. The Map.Entry interface contains the getKey() and getValue() methods. But,
we should call the entrySet() method of Map interface to get the instance of
Map.Entry.
1. import java.util.*;
2. public class HashMapExample2{
3. public static void main(String args[]){
4. HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating Hash
Map
5. map.put(1,"Mango"); //Put elements in Map
6. map.put(2,"Apple");
7. map.put(3,"Banana");
8. map.put(1,"Grapes"); //trying duplicate key
9.
10. System.out.println("Iterating Hashmap...");
11. for(Map.Entry m : map.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
Iterating Hashmap...
1 Grapes
2 Apple
3 Banana
1. import java.util.*;
2. class HashMap1{
3. public static void main(String args[]){
4. HashMap<Integer,String> hm=new HashMap<Integer,String>();
5. System.out.println("Initial list of elements: "+hm);
6. hm.put(100,"Amit");
7. hm.put(101,"Vijay");
8. hm.put(102,"Rahul");
9.
10. System.out.println("After invoking put() method ");
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14.
15. hm.putIfAbsent(103, "Gaurav");
16. System.out.println("After invoking putIfAbsent() method ");
17. for(Map.Entry m:hm.entrySet()){
18. System.out.println(m.getKey()+" "+m.getValue());
19. }
20. HashMap<Integer,String> map=new HashMap<Integer,String>();
21. map.put(104,"Ravi");
22. map.putAll(hm);
23. System.out.println("After invoking putAll() method ");
24. for(Map.Entry m:map.entrySet()){
25. System.out.println(m.getKey()+" "+m.getValue());
26. }
27. }
28. }
Initial list of elements: {}
After invoking put() method
100 Amit
101 Vijay
102 Rahul
After invoking putIfAbsent() method
100 Amit
101 Vijay
102 Rahul
103 Gaurav
After invoking putAll() method
100 Amit
101 Vijay
102 Rahul
103 Gaurav
104 Ravi
1. import java.util.*;
2. public class HashMap2 {
3. public static void main(String args[]) {
4. HashMap<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. map.put(103, "Gaurav");
9. System.out.println("Initial list of elements: "+map);
10. //key-based removal
11. map.remove(100);
12. System.out.println("Updated list of elements: "+map);
13. //value-based removal
14. map.remove(101);
15. System.out.println("Updated list of elements: "+map);
16. //key-value pair based removal
17. map.remove(102, "Rahul");
18. System.out.println("Updated list of elements: "+map);
19. }
20. }
Output:
1. import java.util.*;
2. class HashMap3{
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. System.out.println("Initial list of elements:");
9. for(Map.Entry m:hm.entrySet())
10. {
11. System.out.println(m.getKey()+" "+m.getValue());
12. }
13. System.out.println("Updated list of elements:");
14. hm.replace(102, "Gaurav");
15. for(Map.Entry m:hm.entrySet())
16. {
17. System.out.println(m.getKey()+" "+m.getValue());
18. }
19. System.out.println("Updated list of elements:");
20. hm.replace(101, "Vijay", "Ravi");
21. for(Map.Entry m:hm.entrySet())
22. {
23. System.out.println(m.getKey()+" "+m.getValue());
24. }
25. System.out.println("Updated list of elements:");
26. hm.replaceAll((k,v) -> "Ajay");
27. for(Map.Entry m:hm.entrySet())
28. {
29. System.out.println(m.getKey()+" "+m.getValue());
30. }
31. }
32. }
Initial list of elements:
100 Amit
101 Vijay
102 Rahul
Updated list of elements:
100 Amit
101 Vijay
102 Gaurav
Updated list of elements:
100 Amit
101 Ravi
102 Gaurav
Updated list of elements:
100 Ajay
101 Ajay
102 Ajay
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class MapExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new HashMap<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Gr
aw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(1,b1);
24. map.put(2,b2);
25. map.put(3,b3);
26.
27. //Traversing map
28. for(Map.Entry<Integer, Book> entry:map.entrySet()){
29. int key=entry.getKey();
30. Book b=entry.getValue();
31. System.out.println(key+" Details:");
32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantit
y);
33. }
34. }
35. }
Output:
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications and Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6
What is Hashing
It is the process of converting an object into an integer value. The integer value helps
in indexing and faster searches.
What is HashMap
HashMap is a part of the Java collection framework. It uses a technique called
Hashing. It implements the map interface. It stores the data in the pair of Key and
Value. HashMap contains an array of the nodes, and the node is represented as a
class. It uses an array and LinkedList data structure internally for storing Key and
Value. There are four fields in HashMap.
o equals(): It checks the equality of two objects. It compares the Key, whether they are
equal or not. It is a method of the Object class. It can be overridden. If you override
the equals() method, then it is mandatory to override the hashCode() method.
o hashCode(): This is the method of the object class. It returns the memory reference
of the object in integer form. The value received from the method is used as the
bucket number. The bucket number is the address of the element inside the map.
Hash code of null Key is 0.
o Buckets: Array of the node is called buckets. Each node has a data structure like a
LinkedList. More than one node can share the same bucket. It may be different in
capacity.
Insert Key, Value pair in HashMap
We use put() method to insert the Key and Value pair in the HashMap. The default
size of HashMap is 16 (0 to 15).
Example
In the following example, we want to insert three (Key, Value) pair in the HashMap.
Let's see at which index the Key, value pair will be saved into HashMap. When we call
the put() method, then it calculates the hash code of the Key "Aman." Suppose the
hash code of "Aman" is 2657860. To store the Key in memory, we have to calculate
the index.
Calculating Index
Index minimizes the size of the array. The Formula for calculating the index is:
1. Index = hashcode(Key) & (n-1)
Where n is the size of the array. Hence the index value for "Aman" is:
The value 4 is the computed index value where the Key and value will store in
HashMap.
Hash Collision
This is the case when the calculated index value is the same for two or more Keys.
Let's calculate the hash code for another Key "Sunny." Suppose the hash code for
"Sunny" is 63281940. To store the Key in the memory, we have to calculate index by
using the index formula.
The value 4 is the computed index value where the Key will be stored in HashMap. In
this case, equals() method check that both Keys are equal or not. If Keys are same,
replace the value with the current value. Otherwise, connect this node object to the
existing node object through the LinkedList. Hence both Keys will be stored at index
4.
Similarly, we will store the Key "Ritesh." Suppose hash code for the Key is 2349873.
The index value will be 1. Hence this Key will be stored at index 1.
Suppose we have to fetch the Key "Aman." The following method will be called.
1. map.get(new Key("Aman"));
It generates the hash code as 2657860. Now calculate the index value of 2657860 by
using index formula. The index value will be 4, as we have calculated above. get()
method search for the index value 4. It compares the first element Key with the given
Key. If both keys are equal, then it returns the value else check for the next element
in the node if it exists. In our scenario, it is found as the first element of the node and
return the value 19.
The hash code of the Key "Sunny" is 63281940. The calculated index value of
63281940 is 4, as we have calculated for put() method. Go to index 4 of the array and
compare the first element's Key with the given Key. It also compares Keys. In our
scenario, the given Key is the second element, and the next of the node is null. It
compares the second element Key with the specified Key and returns the value 29. It
returns null if the next of the node is null.
But there are many differences between HashMap and Hashtable classes that are
given below.
HashMap Hashtable
2) HashMap allows one null key and multiple null Hashtable doesn't allow any
values. null key or value.
o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class
Collections class provides static methods for sorting the elements of collections. If
collection elements are of Set or Map, we can use TreeSet or TreeMap. However, we
cannot sort the elements of List. Collections class provides methods for sorting the
elements of List type elements.
File: Student.java
File: TestSort1.java
1. import java.util.*;
2. public class TestSort1{
3. public static void main(String args[]){
4. ArrayList<Student> al=new ArrayList<Student>();
5. al.add(new Student(101,"Vijay",23));
6. al.add(new Student(106,"Ajay",27));
7. al.add(new Student(105,"Jai",21));
8.
9. Collections.sort(al);
10. for(Student st:al){
11. System.out.println(st.rollno+" "+st.name+" "+st.age);
12. }
13. }
14. }
105 Jai 21
101 Vijay 23
106 Ajay 27
File: Student.java
1. import java.util.*;
2. public class TestSort2{
3. public static void main(String args[]){
4. ArrayList<Student> al=new ArrayList<Student>();
5. al.add(new Student(101,"Vijay",23));
6. al.add(new Student(106,"Ajay",27));
7. al.add(new Student(105,"Jai",21));
8.
9. Collections.sort(al);
10. for(Student st:al){
11. System.out.println(st.rollno+" "+st.name+" "+st.age);
12. }
13. }
14. }
106 Ajay 27
101 Vijay 23
105 Jai 21
Comparable Comparator
5) We can sort the list elements of Comparable We can sort the list elements of
type by Collections.sort(List) method. Comparator type
by Collections.sort(List,
Comparator) method.
File: TestSort3.java
Output:
105 Jai 21
101 Vijay 23
106 Ajay 27
Student.java
1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }
AgeComparator.java
1. import java.util.*;
2. class AgeComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. if(s1.age==s2.age)
5. return 0;
6. else if(s1.age>s2.age)
7. return 1;
8. else
9. return -1;
10. }
11. }
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using
the compareTo() method of String class, which internally provides the comparison
logic.
1. import java.util.*;
2. class NameComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. return s1.name.compareTo(s2.name);
5. }
6. }
TestComparator.java
In this class, we are printing the values of the object by sorting on the basis of name
and 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
Method Description
public void load(InputStream is) It loads data from the InputStream object
public String getProperty(String key, It searches for the property with the specified
String defaultValue) key.
public void list(PrintWriter out)) It is used to print the property list out to the
specified output stream.
public void store(Writer w, String It writes the properties in the writer object.
comment)
public void storeToXML(Writer w, It writes the properties in the writer object for
String comment, String encoding) generating XML document with the specified
encoding.
db.properties
1. user=system
2. password=oracle
Now, let's create the java class to read the data from the properties file.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("db.properties");
6.
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }
Output:system
oracle
Now if you change the value of the properties file, you don't need to recompile the
java class. That means no maintenance problem.
Test.java
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=System.getProperties();
7. Set set=p.entrySet();
8.
9. Iterator itr=set.iterator();
10. while(itr.hasNext()){
11. Map.Entry entry=(Map.Entry)itr.next();
12. System.out.println(entry.getKey()+" = "+entry.getValue());
13. }
14.
15. }
16. }
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
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
1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=new Properties();
7. p.setProperty("name","Sonoo Jaiswal");
8. p.setProperty("email","[email protected]");
9.
10. p.store(new FileWriter("info.properties"),"Javatpoint Properties Example");
11.
12. }
13. }
info.properties
1. #Javatpoint Properties Example
2. #Thu Oct 03 22:35:53 IST 2013
3. [email protected]
4. name=Sonoo Jaiswal