java.text.DateFormat Fields
protected Calendar calendar
protected NumberFormat numberFormat
public static final int ERA_FIELD
public static final int YEAR_FIELD
public static final int MONTH_FIELD
public static final int DATE_FIELD
public static final int HOUR_OF_DAY1_FIELD
public static final int HOUR_OF_DAY0_FIELD
public static final int MINUTE_FIELD
public static final int SECOND_FIELD
public static final int MILLISECOND_FIELD
public static final int DAY_OF_WEEK_FIELD
public static final int DAY_OF_YEAR_FIELD
public static final int DAY_OF_WEEK_IN_MONTH_FIELD
public static final int WEEK_OF_YEAR_FIELD
public static final int WEEK_OF_MONTH_FIELD
public static final int AM_PM_FIELD
public static final int HOUR1_FIELD
public static final int HOUR0_FIELD
public static final int TIMEZONE_FIELD
public static final int FULL
public static final int LONG
public static final int MEDIUM
public static final int SHORT
public static final int DEFAULT
java.text.DateFormat Methods
No. Public Method Description
1) final String format(Date date) converts given Date object into string.
2) Date parse(String converts string into Date object.
source)throws ParseException
3) static final DateFormat returns time formatter with default formatting style for the default loca
getTimeInstance()
4) static final DateFormat returns time formatter with the given formatting style for the default lo
getTimeInstance(int style)
5) static final DateFormat returns time formatter with the given formatting style for the given loc
getTimeInstance(int style,
Locale locale)
6) static final DateFormat returns date formatter with default formatting style for the default loca
getDateInstance()
7) static final DateFormat returns date formatter with the given formatting style for the default lo
getDateInstance(int style)
8) static final DateFormat returns date formatter with the given formatting style for the given loc
getDateInstance(int style,
Locale locale)
9) static final DateFormat returns date/time formatter with default formatting style for the default
getDateTimeInstance()
10) static final DateFormat returns date/time formatter with the given date formatting style and tim
getDateTimeInstance(int the default locale.
dateStyle,int timeStyle)
11) static final DateFormat returns date/time formatter with the given date formatting style and tim
getDateTimeInstance(int the given locale.
dateStyle, int timeStyle,
Locale locale) returns date/time formatter with short formatting style for date and tim
returns an array of available locales.
12) static final DateFormat returns an instance of Calendar for this DateFormat instance.
getInstance() returns an instance of NumberFormat for this DateFormat instance.
returns an instance of TimeZone for this DateFormat instance.
13) static Locale[]
getAvailableLocales()
14) Calendar getCalendar()
15) NumberFormat
getNumberFormat()
16) TimeZone getTimeZone()
Java DateFormat Example: Date to String
Let's see the simple example to format date and time in java using java.text.DateFormat
class.
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
Date currentDate = new Date();
System.out.println("Current Date: "+currentDate);
String dateToStr = DateFormat.getInstance().format(currentDate);
System.out.println("Date Format using getInstance(): "+dateToStr);
}
}
Output:
Current Date: Tue Mar 31 14:37:23 IST 2015
Date Format using getInstance(): 31/3/15 2:37 PM
Let's see the full example to format date and time in java using java.text.DateFormat class.
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample2 {
public static void main(String[] args) {
Date currentDate = new Date();
System.out.println("Current Date: "+currentDate);
String dateToStr = DateFormat.getInstance().format(currentDate);
System.out.println("Date Format using getInstance(): "+dateToStr);
dateToStr = DateFormat.getDateInstance().format(currentDate);
System.out.println("Date Format using getDateInstance(): "+dateToStr);
dateToStr = DateFormat.getTimeInstance().format(currentDate);
System.out.println("Date Format using getTimeInstance(): "+dateToStr);
dateToStr = DateFormat.getDateTimeInstance().format(currentDate);
System.out.println("Date Format using getDateTimeInstance(): "+dateToStr);
dateToStr = DateFormat.getTimeInstance(DateFormat.SHORT).format(currentDate);
System.out.println("Date Format using getTimeInstance(DateFormat.SHORT):
"+dateToStr);
dateToStr = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(currentDate);
System.out.println("Date Format using getTimeInstance(DateFormat.MEDIUM):
"+dateToStr);
dateToStr = DateFormat.getTimeInstance(DateFormat.LONG).format(currentDate);
System.out.println("Date Format using getTimeInstance(DateFormat.LONG):
"+dateToStr);
dateToStr =
DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.SHORT).format(currentD
ate);
System.out.println("Date Format using
getDateTimeInstance(DateFormat.LONG,DateFormat.SHORT): "+dateToStr);
}
}
Output:
Current Date: Tue Mar 31 14:37:23 IST 2015
Date Format using getInstance(): 31/3/15 2:37 PM
Date Format using getDateInstance(): 31 Mar, 2015
Date Format using getTimeInstance(): 2:37:23 PM
Date Format using getDateTimeInstance(): 31 Mar, 2015 2:37:23 PM
Date Format using getTimeInstance(DateFormat.SHORT): 2:37 PM
Date Format using getTimeInstance(DateFormat.MEDIUM): 2:37:23 PM
Date Format using getTimeInstance(DateFormat.LONG): 2:37:23 PM IST
Date Format using getDateTimeInstance(DateFormat.LONG,DateFormat.SHORT): 31
March, 2015 2:37 PM
Java DateFormat Example: String to Date
Let's see the simple example to convert string into date using java.text.DateFormat class.
import java.text.DateFormat;
import java.util.Date;
public class DateFormatExample3 {
public static void main(String[] args)throws Exception {
Date d = DateFormat.getDateInstance().parse("31 Mar, 2015");
System.out.println("Date is: "+d);
}
}
Output:
Date is: Tue Mar 31 00:00:00 IST 2015
Java SimpleDateFormat
The java.text.SimpleDateFormat class provides methods to format and parse date and time
in java. The SimpleDateFormat is a concrete class for formatting and parsing date which
inherits java.text.DateFormat class.
Notice that formatting means converting date to string and parsing means converting string
to date.
Java SimpleDateFormat Example: Date to String
Let's see the simple example to format date in java using java.text.SimpleDateFormat class.
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formatter.format(date);
System.out.println(strDate);
}
}
Test it Now
Output:
13/04/2015
Note: M (capital M) represents month and m (small m) represents minute in java.
Let's see the full example to format date and time in java using java.text.SimpleDateFormat
class.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SimpleDateFormatExample2 {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println("Date Format with MM/dd/yyyy : "+strDate);
formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
strDate = formatter.format(date);
System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
strDate = formatter.format(date);
System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);
}
}
Test it Now
Output:
Date Format with MM/dd/yyyy : 04/13/2015
Date Format with dd-M-yyyy hh:mm:ss : 13-4-2015 10:59:26
Date Format with dd MMMM yyyy : 13 April 2015
Date Format with dd MMMM yyyy zzzz : 13 April 2015 India Standard Time
Date Format with E, dd MMM yyyy HH:mm:ss z : Mon, 13 Apr 2015 22:59:26 IST
Java SimpleDateFormat Example: String to Date
Let's see the simple example to convert string into date using java.text.SimpleDateFormat
class.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample3 {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
Date date = formatter.parse("31/03/2015");
System.out.println("Date is: "+date);
} catch (ParseException e) {e.printStackTrace();}
}
}
Test it Now
Output:
Date is: Tue Mar 31 00:00:00 IST 2015
15.4 Current date and Time
There are many ways to get current date and time in java. There are many classes that can
be used to get current date and time in java.
java.time.format.DateTimeFormatter class
java.text.SimpleDateFormat class
java.time.LocalDate class
java.time.LocalTime class
java.time.LocalDateTime class
java.time.Clock class
java.util.Date class
java.sql.Date class
java.util.Calendar class
Get Current Date and Time: java.time.format.DateTimeFormatter
The LocalDateTime.now() method returns the instance of LocalDateTime class. If we print
the instance of LocalDateTime class, it prints current date and time. To format the current
date, you can use DateTimeFormatter class which is included in JDK 1.8.
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class CurrentDateTimeExample1 {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
}
}
Test it Now
Output:
2017/11/06 12:11:58
Get Current Date and Time: java.text.SimpleDateFormat
The SimpleDateFormat class is also used for formatting date and time. But it is old
approach.
import java.text.SimpleDateFormat;
import java.util.Date;
public class CurrentDateTimeExample2 {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(formatter.format(date));
}
}
Test it Now
Output:
06/11/2017 12:26:18
Get Current Date: java.time.LocalDate
The LocalDate.now() method returns the instance of LocalDate class. If we print the instance
of LocalDate class, it prints current date.
System.out.println(java.time.LocalDate.now());
Output:
2017-01-23
Get Current Time: java.time.LocalTime
The LocalTime.now() method returns the instance of LocalTime class. If we print the
instance of LocalTime class, it prints current time.
System.out.println(java.time.LocalTime.now());
Output:
00:01:14.341
Get Current Date & Time: java.time.LocalDateTime
The LocalDateTime.now() method returns the instance of LocalDateTime class. If we print
the instance of LocalDateTime class, it prints current date and time both.
System.out.println(java.time.LocalDateTime.now());
Output:
2017-01-24T00:03:31.593
Get Current Date & Time: java.time.Clock
The Clock.systemUTC().instant() method returns current date and time both.
System.out.println(java.time.Clock.systemUTC().instant());
Output:
2017-01-23T18:35:23.669Z
Get Current Date & Time: java.util.Date
By printing the instance of java.util.Date class, you can print current date and time in java.
There are two ways to do so.
1st way:
java.util.Date date=new java.util.Date();
System.out.println(date);
2nd way:
long millis=System.currentTimeMillis();
java.util.Date date=new java.util.Date(millis);
System.out.println(date);
Output:
Thu Mar 26 08:22:02 IST 2015
Get Current Date: java.sql.Date
By printing the instance of java.sql.Date class, you can print current date in java. It doesn't
print time. This date instance is generally used to save current date in database.
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
System.out.println(date);
Output:
2015-03-26
Get Current Date & Time: java.util.Calendar
Calendar class can be used to get the instance of Date class. The getTime() method of
Calendar class returns the instance of java.util.Date. The Calendar.getInstance() method
returns the instance of Calendar class.
Date date=java.util.Calendar.getInstance().getTime();
System.out.println(date);
Output:
Thu Mar 26 08:22:02 IST 2015
16 Collection in JAVA
16.0 Introduction to collection
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).
What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
It provides readymade architecture.
It represents a set of classes and interfaces.
It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:
Interfaces and its implementations, i.e., classes
Algorithm
16.1 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 List interface here. The ArrayList
maintains the insertion order internally.
It inherits the AbstractList class and implements List interface.
The important points about Java ArrayList class are:
1) Java ArrayList class can contain duplicate elements.
2) Java ArrayList class maintains insertion order.
3) Java ArrayList class is non synchronized.
4) Java ArrayList allows random access because array works at the index basis.
5) In ArrayList, manipulation is little bit slower than the LinkedList in Java
because a lot of shifting needs to occur if any element is removed from the
array list.
Hierarchy of ArrayList class
As shown in the above diagram, Java ArrayList class extends AbstractList class
which implements List interface. The List interface extends the Collection and
Iterable interfaces in hierarchical order.
ArrayList class declaration
Let's see the declaration for java.util.ArrayList class.
public class ArrayList<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, Serializable
Constructor Description
ArrayList() It is used to build an empty array list.
It is used to build an array list that is initialized with the elements of the collection c.
ArrayList(Collection<?
extends E> c) It is used to build an array list that has the specified initial capacity.
ArrayList(int capacity)
Method Description
void add(int index, E element) It is used to insert the specified element at the specified position in a list
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends It is used to append all of the elements in the specified collection to the
E> c) order that they are returned by the specified collection's iterator.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified collection, starting a
extends E> c) of the list.
void clear() It is used to remove all of the elements from this list.
void ensureCapacity(int It is used to enhance the capacity of an ArrayList instance.
requiredCapacity)
E get(int index) It is used to fetch the element from the particular position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
Iterator()
listIterator()
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the spec
the list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list in th
<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this list in th
Object clone() It is used to return a shallow copy of an ArrayList.
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 occurrence of the spec
the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in the l
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super It is used to remove all the elements from the list that satisfies the given
E> filter)
protected void removeRange(int It is used to remove all the elements lies within the given range.
fromIndex, int toIndex)
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the specified elem
operator)
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the spec
E set(int index, E element) It is used to replace the specified element in the list, present at the spec
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of specified compa
Spliterator<E> spliterator() It is used to create spliterator over the elements in a list.
List<E> subList(int fromIndex, int It is used to fetch all the elements lies within the given range.
toIndex)
int size() It is used to return the number of elements present in the list.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be the list's cur
Java ArrayList Example
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
}
}
Iterating ArrayList using Iterator
Let's see an example to traverse ArrayList elements using the Iterator interface.
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}
Iterating ArrayList using For-each loop
Let's see an example to traverse the ArrayList elements using the for-each loop
import java.util.*;
public class ArrayListExample3{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Get and Set ArrayList
The get() method returns the element at the specified index, whereas the set()
method changes the element.
import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element
System.out.println("Returning element: "+al.get(1));//it will return the 2nd element,
because index starts from 0
//changing the element
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);
}
}
How to Sort ArrayList
The java.util package provides a utility class Collections which has the static method
sort(). Using the Collections.sort() method, we can easily sort the ArrayList.
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
}
User-defined class objects in Java ArrayList
Let's see an example where we are storing Student class object in an array list.
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
import java.util.*;
class ArrayList5{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Java ArrayList example to add elements
Here, we see different ways to add an element.
import java.util.*;
class ArrayList7{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
System.out.println("Initial list of elements: "+al);
//Adding elements to the end of the list
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
System.out.println("After invoking add(E e) method: "+al);
//Adding an element at the specific position
al.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) method: "+al);
ArrayList<String> al2=new ArrayList<String>();
al2.add("Sonoo");
al2.add("Hanumat");
//Adding second list elements to the first list
al.addAll(al2);
System.out.println("After invoking addAll(Collection<? extends E> c) method:
"+al);
ArrayList<String> al3=new ArrayList<String>();
al3.add("John");
al3.add("Rahul");
//Adding second list elements to the first list at specific position
al.addAll(1, al3);
System.out.println("After invoking addAll(int index, Collection<? extends E> c)
method: "+al);
}
}
Output:
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]
Java ArrayList example to remove elements
Here, we see different ways to remove an element.
import java.util.*;
class ArrayList8 {
public static void main(String [] args)
{
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al.add("Anuj");
al.add("Gaurav");
System.out.println("An initial list of elements: "+al);
//Removing specific element from arraylist
al.remove("Vijay");
System.out.println("After invoking remove(object) method: "+al);
//Removing element on the basis of specific position
al.remove(0);
System.out.println("After invoking remove(index) method: "+al);
//Creating another arraylist
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
//Adding new elements to arraylist
al.addAll(al2);
System.out.println("Updated list : "+al);
//Removing all the new elements from arraylist
al.removeAll(al2);
System.out.println("After invoking removeAll() method: "+al);
//Removing elements on the basis of specified condition
al.removeIf(str -> str.contains("Ajay")); //Here, we are using Lambda
expression
System.out.println("After invoking removeIf() method: "+al);
//Removing all the elements available in the list
al.clear();
System.out.println("After invoking clear() method: "+al);
}
}
Output:
An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav]
After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
After invoking clear() method: []
Java ArrayList example of retainAll() method
import java.util.*;
class ArrayList9{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
al.retainAll(al2);
System.out.println("iterating the elements after retaining the elements of al2");
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
iterating the elements after retaining the elements of al2
Ravi
Java ArrayList example of isEmpty() method
import java.util.*;
class ArrayList10{
public static void main(String [] args)
{
ArrayList<String> al=new ArrayList<String>();
System.out.println("Is ArrayList Empty: "+al.isEmpty());
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
System.out.println("After Insertion");
System.out.println("Is ArrayList Empty: "+al.isEmpty());
}
}
Output:
Is ArrayList Empty: true
After Insertion
Is ArrayList Empty: false
16.2 Linked List
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.
The important points about Java LinkedList are:
1) Java LinkedList class can contain duplicate elements.
2) Java LinkedList class maintains insertion order.
3) Java LinkedList class is non synchronized.
4) In Java LinkedList class, manipulation is fast because no shifting needs to occur.
5) Java LinkedList class can be used as a list, stack or queue.
Doubly Linked List
In the case of a doubly linked list, we can add or remove elements from both sides.
Let's see the declaration for java.util.LinkedList class.
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>,
Deque<E>, Cloneable, Serializable
Constructor Description
LinkedList() It is used to construct an empty list.
LinkedList(Collection<? extends It is used to construct a list containing the elements of the specified collectio
E> c) returned by the collection's iterator.
Method Description
boolean add(E e) It is used to append the specified element to the end of a list.
void add(int index, E element) It is used to insert the specified element at the specified position index in a list.
boolean addAll(Collection<? It is used to append all of the elements in the specified collection to the end of
extends E> c) that they are returned by the specified collection's iterator.
boolean addAll(Collection<? It is used to append all of the elements in the specified collection to the end of
extends E> c) that they are returned by the specified collection's iterator.
boolean addAll(int index, It is used to append all the elements in the specified collection, starting at the s
Collection<? extends E> c) list.
void addFirst(E e) It is used to insert the given element at the beginning of a list.
void addLast(E e) It is used to append the given element to the end of a list.
void clear() It is used to remove all the elements from a list.
Object clone() It is used to return a shallow copy of an ArrayList.
boolean contains(Object o) It is used to return true if a list contains a specified element.
Iterator<E> It is used to return an iterator over the elements in a deque in reverse sequenti
descendingIterator()
E element() It is used to retrieve the first element of a list.
E get(int index) It is used to return the element at the specified position in a list.
E getFirst() It is used to return the first element in a list.
E getLast() It is used to return the last element in a list.
int indexOf(Object o) It is used to return the index in a list of the first occurrence of the specified elem
does not contain any element.
int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the specified elem
does not contain any element.
ListIterator<E> listIterator(int It is used to return a list-iterator of the elements in proper sequence, starting at
index) in the list.
boolean offer(E e) It adds the specified element as the last element of a list.
boolean offerFirst(E e) It inserts the specified element at the front of a list.
boolean offerLast(E e) It inserts the specified element at the end of a list.
E peek() It retrieves the first element of a list
E peekFirst() It retrieves the first element of a list or returns null if a list is empty.
E peekLast() It retrieves the last element of a list or returns null if a list is empty.
E poll() It retrieves and removes the first element of a list.
E pollFirst() It retrieves and removes the first element of a list, or returns null if a list is empt
E pollLast() It retrieves and removes the last element of a list, or returns null if a list is empt
E pop() It pops an element from the stack represented by a list.
void push(E e) It pushes an element onto the stack represented by a list.
E remove() It is used to retrieve and removes the first element of a list.
E remove(int index) It is used to remove the element at the specified position in a list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element in a list.
E removeFirst() It removes and returns the first element from a list.
boolean It is used to remove the first occurrence of the specified element in a list (when
removeFirstOccurrence(Object head to tail).
o)
E removeLast() It removes and returns the last element from a list.
boolean It removes the last occurrence of the specified element in a list (when traversin
removeLastOccurrence(Object tail).
o)
E set(int index, E element) It replaces the element at the specified position in a list with the specified elem
Object[] toArray() It is used to return an array containing all the elements in a list in proper seque
last element).
<T> T[] toArray(T[] a) It returns an array containing all the elements in the proper sequence (from firs
the runtime type of the returned array is that of the specified array.
int size() It is used to return the number of elements in a list.
Java LinkedList Example
import java.util.*;
public class LinkedList1{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output: Ravi
Vijay
Ravi
Ajay
Java LinkedList example to add elements
Here, we see different ways to add elements.
import java.util.*;
public class LinkedList2{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
System.out.println("Initial list of elements: "+ll);
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
System.out.println("After invoking add(E e) method: "+ll);
//Adding an element at the specific position
ll.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Sonoo");
ll2.add("Hanumat");
//Adding second list elements to the first list
ll.addAll(ll2);
System.out.println("After invoking addAll(Collection<? extends E> c) method: "+ll);
LinkedList<String> ll3=new LinkedList<String>();
ll3.add("John");
ll3.add("Rahul");
//Adding second list elements to the first list at specific position
ll.addAll(1, ll3);
System.out.println("After invoking addAll(int index, Collection<? extends E> c)
method: "+ll);
//Adding an element at the first position
ll.addFirst("Lokesh");
System.out.println("After invoking addFirst(E e) method: "+ll);
//Adding an element at the last position
ll.addLast("Harsh");
System.out.println("After invoking addLast(E e) method: "+ll);
}
}
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]
Java LinkedList example to remove elements
Here, we see different ways to remove an element.
import java.util.*;
public class LinkedList3 {
public static void main(String [] args)
{
LinkedList<String> ll=new LinkedList<String>();
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
ll.add("Anuj");
ll.add("Gaurav");
ll.add("Harsh");
ll.add("Virat");
ll.add("Gaurav");
ll.add("Harsh");
ll.add("Amit");
System.out.println("Initial list of elements: "+ll);
//Removing specific element from arraylist
ll.remove("Vijay");
System.out.println("After invoking remove(object) method: "+ll);
//Removing element on the basis of specific position
ll.remove(0);
System.out.println("After invoking remove(index) method: "+ll);
LinkedList<String> ll2=new LinkedList<String>();
ll2.add("Ravi");
ll2.add("Hanumat");
// Adding new elements to arraylist
ll.addAll(ll2);
System.out.println("Updated list : "+ll);
//Removing all the new elements from arraylist
ll.removeAll(ll2);
System.out.println("After invoking removeAll() method: "+ll);
//Removing first element from the list
ll.removeFirst();
System.out.println("After invoking removeFirst() method: "+ll);
//Removing first element from the list
ll.removeLast();
System.out.println("After invoking removeLast() method: "+ll);
//Removing first occurrence of element from the list
ll.removeFirstOccurrence("Gaurav");
System.out.println("After invoking removeFirstOccurrence() method: "+ll);
//Removing last occurrence of element from the list
ll.removeLastOccurrence("Harsh");
System.out.println("After invoking removeLastOccurrence() method: "+ll);
//Removing all the elements available in the list
ll.clear();
System.out.println("After invoking clear() method: "+ll);
}
}
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: []
Java LinkedList Example to reverse a list of elements
import java.util.*;
public class LinkedList4{
public static void main(String args[]){
LinkedList<String> ll=new LinkedList<String>();
ll.add("Ravi");
ll.add("Vijay");
ll.add("Ajay");
//Traversing the list of elements in reverse order
Iterator i=ll.descendingIterator();
while(i.hasNext())
{
System.out.println(i.next());
}
} LinkedList
}
Output: Ajay
Vijay
Ravi
ArrayList
1) ArrayList internally uses LinkedList internally uses a doubly linked list to store the elements.
a dynamic array to store the
elements. Manipulation with LinkedList is faster than ArrayList
because it uses a doubly linked list, so no bit shifting is
2) Manipulation with ArrayList required in memory.
is slow because it internally
uses an array. If any element is LinkedList class can act as a list and queue both
removed from the array, all the because it implements List and Deque interfaces.
bits are shifted in memory.
LinkedList is better for manipulating data.
3) An ArrayList class can act as
a list only because it
implements List only.
4) ArrayList is better for storing
and accessing data.
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.
List Interface declaration
public interface List<E> extends Collection<E>
Method Description
void add(int index, E element) It is used to insert the specified element at the specified position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? It is used to append all of the elements in the specified collection to the end of
extends E> c)
boolean addAll(int index, It is used to append all the elements in the specified collection, starting at the s
Collection<? extends E> c) the list.
void clear() It is used to remove all of the elements from this list.
boolean equals(Object o) It is used to compare the specified object with the elements of a list.
int hashcode() It is used to return the hash code value for a list.
E get(int index) It is used to fetch the element from the particular position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified el
list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list in the corre
<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this list in the corre
boolean contains(Object o) It returns true if the list contains the specified element
boolean It returns true if the list contains all the specified element
containsAll(Collection<?> c)
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified el
List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
boolean It is used to remove all the elements from the list.
removeAll(Collection<?> c)
void It is used to replace all the elements from the list with the specified element.
replaceAll(UnaryOperator<E>
operator) It is used to retain all the elements in the list that are present in the specified co
void retainAll(Collection<?> c) It is used to replace the specified element in the list, present at the specified po
E set(int index, E element) It is used to sort the elements of the list on the basis of specified comparator.
void sort(Comparator<? super
E> c)
Spliterator<E> spliterator() It is used to create spliterator over the elements in a list.
It is used to fetch all the elements lies within the given range.
List<E> subList(int fromIndex,
int toIndex) It is used to return the number of elements present in the list.
int size()
How to create List
The ArrayList and LinkedList classes provide the implementation of List interface. Let's see
the examples to create the List:
//Creating a List of type String using ArrayList
List<String> list=new ArrayList<String>();
//Creating a List of type Integer using ArrayList
List<Integer> list=new ArrayList<Integer>();
//Creating a List of type Book using ArrayList
List<Book> list=new ArrayList<Book>();
//Creating a List of type String using LinkedList
List<String> list=new LinkedList<String>();
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.
Java List Example
Let's see a simple example of List where we are using the ArrayList class as the
implementation.
import java.util.*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Test it Now
Output:
Mango
Apple
Banana
Grapes
How to convert Array to List
We can convert the Array to List by traversing the array and adding the element in list one by
one using list.add() method. Let's see a simple example to convert array elements into List.
import java.util.*;
public class ArrayToListExample{
public static void main(String args[]){
//Creating Array
String[] array={"Java","Python","PHP","C++"};
System.out.println("Printing Array: "+Arrays.toString(array));
//Converting Array to List
List<String> list=new ArrayList<String>();
for(String lang:array){
list.add(lang);
}
System.out.println("Printing List: "+list);
}
}
Test it Now
Output:
Printing Array: [Java, Python, PHP, C++]
Printing List: [Java, Python, PHP, C++]
How to convert List to Array
We can convert the List to Array by calling the list.toArray() method. Let's see a simple
example to convert list elements into array.
import java.util.*;
public class ListToArrayExample{
public static void main(String args[]){
List<String> fruitList = new ArrayList<>();
fruitList.add("Mango");
fruitList.add("Banana");
fruitList.add("Apple");
fruitList.add("Strawberry");
//Converting ArrayList to Array
String[] array = fruitList.toArray(new String[fruitList.size()]);
System.out.println("Printing Array: "+Arrays.toString(array));
System.out.println("Printing List: "+fruitList);
}
}
Test it Now
Output:
Printing Array: [Mango, Banana, Apple, Strawberry]
Printing List: [Mango, Banana, Apple, Strawberry]
Get and Set Element in List
The get() method returns the element at the given index, whereas the set() method changes
or replaces the element.
import java.util.*;
public class ListExample2{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();
//Adding elements in the List
list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//accessing the element
System.out.println("Returning element: "+list.get(1));//it will return the 2nd element, because
index starts from 0
//changing the element
list.set(1,"Dates");
//Iterating the List element using for-each loop
for(String fruit:list)
System.out.println(fruit);
}
}
Test it Now
Output:
Returning element: Apple
Mango
Dates
Banana
Grapes
How to Sort List
There are various ways to sort the List, here we are going to use Collections.sort() method to
sort the list element. The java.util package provides a utility class Collections which has the
static method sort(). Using the Collections.sort() method, we can easily sort any List.
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);
System.out.println("Sorting numbers...");
//Creating a list of numbers
List<Integer> list2=new ArrayList<Integer>();
list2.add(21);
list2.add(11);
list2.add(51);
list2.add(1);
//Sorting the list
Collections.sort(list2);
//Traversing list through the for-each loop
for(Integer number:list2)
System.out.println(number);
}
}
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
Java ListIterator Interface
ListIterator Interface is used to traverse the element in a backward and forward direction.
ListIterator Interface declaration
public interface ListIterator<E> extends Iterator<E>
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
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 c
boolean hasPrevious() This method returns true if this list iterator has more elements while traversing the list in
E previous() This method returns the previous element in the list and moves the cursor position back
E previousIndex() This method returns the index of the element that would be returned by a subsequent c
void remove() This method removes the last element from the list that was returned by next() or previo
void set(E e) This method replaces the last element returned by next() or previous() methods with the
Example of ListIterator Interface
import java.util.*;
public class ListIteratorExample1{
public static void main(String args[]){
List<String> al=new ArrayList<String>();
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
ListIterator<String> itr=al.listIterator();
System.out.println("Traversing elements in forward direction");
while(itr.hasNext()){
System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());
}
System.out.println("Traversing elements in backward direction");
while(itr.hasPrevious()){
System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());
}
}
}
16.4 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.
The important points about Java HashSet class are:
HashSet stores the elements by using a mechanism called hashing.
HashSet contains unique elements only.
HashSet allows null value.
HashSet class is non synchronized.
HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of
their hashcode.
HashSet is the best approach for search operations.
The initial default capacity of HashSet is 16, and the load factor is 0.75.
Difference between List and Set
A list can contain duplicate elements whereas Set contains unique elements only.
HashSet class declaration
Let's see the declaration for java.util.HashSet class.
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,
Serializable
SN Constructor Description
1) HashSet() It is used to construct a default HashSet.
2) HashSet(int capacity)
It is used to initialize the capacity of the hash set to the given integer value ca
3) HashSet(int capacity, grows automatically as elements are added to the HashSet.
float loadFactor)
It is used to initialize the capacity of the hash set to the given integer value ca
4) HashSet(Collection<? specified load factor.
extends E> c)
It is used to initialize the hash set by using the elements of the collection c.
SN Modifier & Method Description
Type
1) boolean add(E e) It is used to add the specified element to this set if it is not a
2) void
3) object clear() It is used to remove all of the elements from the set.
4) boolean clone() It is used to return a shallow copy of this HashSet instance:
themselves are not cloned.
5) boolean
6) Iterator<E> contains(Object It is used to return true if this set contains the specified elem
7) boolean o)
8) int
9) Spliterator<E> isEmpty() It is used to return true if this set contains no elements.
iterator() It is used to return an iterator over the elements in this set.
remove(Object o) It is used to remove the specified element from this set if it
size() It is used to return the number of elements in the set.
spliterator() It is used to create a late-binding and fail-fast Spliterator ov
set.
Java HashSet Example
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered
collection.
import java.util.*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Five
One
Four
Two
Three
Java HashSet example ignoring duplicate elements
In this example, we see that HashSet doesn't allow duplicate elements.
import java.util.*;
class HashSet2{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ajay
Vijay
Ravi
Java HashSet example to remove elements
Here, we see different ways to remove an element.
import java.util.*;
class HashSet3{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Arun");
set.add("Sumit");
System.out.println("An initial list of elements: "+set);
//Removing specific element from HashSet
set.remove("Ravi");
System.out.println("After invoking remove(object) method: "+set);
HashSet<String> set1=new HashSet<String>();
set1.add("Ajay");
set1.add("Gaurav");
set.addAll(set1);
System.out.println("Updated List: "+set);
//Removing all the new elements from HashSet
set.removeAll(set1);
System.out.println("After invoking removeAll() method: "+set);
//Removing elements on the basis of specified condition
set.removeIf(str->str.contains("Vijay"));
System.out.println("After invoking removeIf() method: "+set);
//Removing all the elements available in the set
set.clear();
System.out.println("After invoking clear() method: "+set);
}
}
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: []
Java HashSet from another Collection
import java.util.*;
class HashSet4{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Ravi");
list.add("Vijay");
list.add("Ajay");
HashSet<String> set=new HashSet(list);
set.add("Gaurav");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Vijay
Ravi
Gaurav
Ajay
16.5 LinkedHashset
Java LinkedHashSet class is a Hashtable and Linked list implementation of the set interface.
It inherits HashSet class and implements Set interface.
The important points about Java LinkedHashSet class are:
Java LinkedHashSet class contains unique elements only like HashSet.
Java LinkedHashSet class provides all optional set operation and permits null elements.
Java LinkedHashSet class is non synchronized.