KEMBAR78
Unit - IV - I - O, Generics, String Handling and Collections | PDF | Class (Computer Programming) | Parameter (Computer Programming)
0% found this document useful (0 votes)
86 views78 pages

Unit - IV - I - O, Generics, String Handling and Collections

This document covers key concepts in Java including I/O basics, generics, string handling, and collections. It explains how to read and write data using streams, the significance of generics for code reusability and type safety, and provides an overview of string manipulation methods and collection frameworks. Examples are provided for practical understanding of these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views78 pages

Unit - IV - I - O, Generics, String Handling and Collections

This document covers key concepts in Java including I/O basics, generics, string handling, and collections. It explains how to read and write data using streams, the significance of generics for code reusability and type safety, and provides an overview of string manipulation methods and collection frameworks. Examples are provided for practical understanding of these concepts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Unit – IV - I/O, Generics, String Handling and

Collections

1. I/O Basics – Reading and Writing


Console I/O – Reading and Writing Files.
2. Generics: Introduction – Example –
Parameters –General Form – Generic
Methods, Constructors and Interfaces.
3. Strings: Basic String class, methods
and String Buffer Class.
4. Collection frameworks: Overview–
Collection Interfaces – Collection Classes.

1. I/O Basics – Reading and Writing


Console I/O – Reading and Writing Files.
STUDY MATERIAL

I/O Basics

The java.io package contains all the classes


required for input and output operations.
Stream

A stream is a sequence of data. In Java, a stream is


composed of bytes.
3 streams are created for us automatically. All
these streams are attached with the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
1.System.out.println("simple message");
2.System.err.println("error message");

OutputStream vs InputStream
OutputStream InputStream

Java applications use an Java applications use an


output stream to write input stream to read
data to a destination; it data from a source; it
may be a file, an array, may be a file, an array,
peripheral device or peripheral device or
socket. socket.

OutputStream class is InputStream class is an


an abstract class. It is abstract class. It is the
the superclass of all superclass of all classes
classes representing an representing an input
output stream of bytes. stream of bytes.
An output stream
accepts output bytes
and sends them to some
sink.

methods of OutputStream

1) public void is used to write a byte to


write(int)throws the current output stream.
IOException

2) public void is used to write an array of


write(byte[])throws byte to the current output
IOException stream.

3) public void flushes the current output


flush()throws
IOException stream.

4) public void is used to close the current


close()throws output stream.
IOException

methods of InputStream

Method Description

1) public reads the next byte of data


abstract int from the input stream. It
read()throws returns -1 at the end of the file.
IOException

2) public int returns an estimate of the


available()throw number of bytes that can be
s IOException read from the current input
stream.

3) public void is used to close the current


close()throws input stream.
IOException
Example1:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFile
{
public static void main(String args[]) throws
IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1)
{
out.write(c);
}
}
finally
{
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}

Output:
Input.txt: This is test for copy file.

output .txt: This is test for copy file.


Reading and Writing Files
Reading Files:
The Reader class of the java.io package is an
abstract superclass that represents a stream of
characters.
Since Reader is an abstract class, it is not useful by
itself. However, its subclasses can be used to read
data.

Subclasses of Reader

In order to use the functionality of Reader, we can


use its subclasses. Some of them are:
● BufferedReader
● InputStreamReader
● FileReader
● StringReader
Create a Reader

In order to create a Reader, we must import the


java.io.Reader package first. Once we import the
package, here is how we can create the reader.
// Creates a Reader
Reader input = new FileReader();

Methods of Reader

The Reader class provides different methods that


are implemented by its subclasses. Here are some
of the commonly used methods:
● ready() - checks if the reader is ready to be
read
● read(char[] array) - reads the characters from
the stream and stores in the specified array
● read(char[] array, int start, int length) - reads
the number of characters equal to length from
the stream and stores in the specified array
starting from the start
● mark() - marks the position in the stream up to
which data has been read
● reset() - returns the control to the point in the
stream where the mark is set
● skip() - discards the specified number of
characters from the stream
Example:
Input.txt: This is a line of text inside the file.
import java.io.Reader;
import java.io.FileReader;
class Main
{
public static void main(String[] args) {
// Creates an array of character
char[] array = new char[100];
try {
// Creates a reader using the FileReader
Reader input = new FileReader("input.txt");
// Checks if reader is ready
System.out.println("Is there data in the stream? "
+ input.ready());
// Reads characters
input.read(array);
System.out.println("Data in the stream:");
System.out.println(array);
// Closes the reader
input.close();
}
catch(Exception e) { e.getStackTrace();
} }}
Output:
Is there data in the stream? true
Data in the stream:This is a line of text inside the
file.
Java Writer Class
The Writer class of the java.io package is an
abstract superclass that represents a stream of
characters.
Since Writer is an abstract class, it is not useful by
itself. However, its subclasses can be used to write
data.

Subclasses of Writer

In order to use the functionality of the Writer, we


can use its subclasses. Some of them are:
● BufferedWriter
● OutputStreamWriter
● FileWriter
● StringWriter

Create a Writer

In order to create a Writer, we must import the


java.io.Writer package first. Once we import the
package, here is how we can create the writer.
// Creates a Writer
Writer output = new FileWriter();
Here, we have created a writer named output using
the FileWriter class. It is because the Writer is an
abstract class. Hence we cannot create an object of
Writer.
Note: We can also create writers from other
subclasses of the Writer class.

Methods of Writer

The Writer class provides different methods that


are implemented by its subclasses. Here are some
of the methods:
● write(char[] array) - writes the characters from
the specified array to the output stream
● write(String data) - writes the specified string
to the writer
● append(char c) - inserts the specified character
to the current writer
● flush() - forces to write all the data present in
the writer to the corresponding destination
● close() - closes the writer
Example:
import java.io.FileWriter;
import java.io.Writer;
public class Main
{

public static void main(String args[]) {


String data = "This is the data in the output
file";
try { // Creates a Writer using FileWriter
Writer output = new
FileWriter("output.txt");
// Writes string to the file
output.write(data);
// Closes the writer
output.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
OUTPUT:
Writer output = new FileWriter("output.txt");

Strings
Basic String class,
methods and String Buffer Class.

String
Strings is an objects that can hold a sequence of
characters contained within a pair of double
quotes ("). It is not a primitive data type.
The java.lang.String class is used to create a
string object.
Syntax:
Datatype variable name=”Hello World”;
Example: String greeting = "Hello world!";
Example1:
public class St
{
public static void main(String args[])
{
char[] a = { 'H', 'e', 'l', 'l', 'o', '.' };
String b = new String(a);
System.out.println(b);
}
}
Output: Hello Online Compiler
The String class is immutable, so that once it is
created a String object cannot be changed.
If there is a necessity to make a lot of modifications
to Strings of characters, then you should use String
Buffer & String Builder Classes.
String Handling Functions:

Function Definition
string.charAt() Returns the character at the
given index in the string.
int length() It returns string length

static String format(String It returns a formatted string.


format, Object... args)

static String format(Locale l, It returns a formatted string


String format, Object... args) with a given locale.

String concat(String str) It concatenates the specified


string.

String replace(char old, char It replaces all occurrences of


new) the specified char value.

int indexOf(int ch) It returns the specified char


value index.

int indexOf(String substring) It returns the specified


substring index.

String toLowerCase() It returns a string in


lowercase.

String toUpperCase() It returns a string in


uppercase.

String trim() It removes the beginning and


ending spaces of this string.

charAt(), compareTo(), concat(), endswith(),


equals(), equalsignorecase(), format(),
getBytes(), getChars(), indexOf(), isEmpty(),
join(), length(), replace(), replaceall(),
spilt(),..
Example:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method
appends the string at the end
System.out.println(s);//will print Sachin because
strings are immutable objects
}
}
Output: Sachin

Example2:
class Testimmutablestring1
{
public static void main(String args[])
{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
Output: Sachin Tendulkar
String compare

It is used in authentication (by equals() method),


sorting (by compareTo() method), reference
matching (by == operator) etc.

There are three ways to compare String in Java:

1. By Using equals() Method

2. By Using == Operator

3. By compareTo() Method

4. public boolean equals(Object another)


compares this string to the specified object.

5. public boolean equalsIgnoreCase(String


another) compares this string to another
string, ignoring case.

Example:

class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Output: true
true
false
Example3
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both
refer to same instance)
System.out.println(s1==s3);//false(because s3
refers to instance created in nonpool)
}
}
Output: true
false

By Using compareTo() method

The String class compareTo() method compares


values lexicographically and returns an integer
value that describes if first string is less than, equal
to or greater than second string.

Suppose s1 and s2 are two String objects. If:

○ s1 == s2 : The method returns 0.

○ s1 > s2 : The method returns a positive value.


○ s1 < s2 : The method returns a negative
value.

Example
class Teststringcomparison4
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0

System.out.println(s1.compareTo(s3));//1(because
s1>s3)
System.out.println(s3.compareTo(s1));//-
1(because s3 < s1 )
}
}
Output: 0
1
-1
Sub-string:
public class Substr1
{
public static void main(String args[])
{
String Str = new String("Welcome to
geeksforgeeks");
System.out.print("The extracted substring is : ");
System.out.println(Str.substring(10));
}
}
Output:
The extracted substring is : geeksforgeeks

import java.lang.*;
import java.io.*;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
String a = "JAVA";
String b="Programming";
int r;
System.out.println(a);
System.out.println(b);
// conversion from String object to StringBuffer
StringBuffer c = new StringBuffer(a);
StringBuffer d = new StringBuffer(b);
// To reverse the string
c.reverse();
d.reverse();
System.out.println(c);
System.out.println(d);
//upper case to lower
System.out.println(a.toLowerCase());
System.out.println(b.toUpperCase());
//length of the string
r=b.length();
System.out.println("Length of B
is"+b.length());
r=a.length();
System.out.println("Length of A
is"+a.length());

}
}

Output:
JAVA
ProgrammingAVAJ
gnimmargorP
java
PROGRAMMING
Length of B is11
Length of A is4

2. Generics
Introduction – Example –Parameters –
General Form – Generic Methods,
Constructors and Interfaces.
Generic:
Generics means parameterized types. The
idea is to allow type (Integer, String, … etc.,
and user-defined types) to be a parameter
to methods, classes, and interfaces.
Java Generics allows us to create a single
class, interface, and method that can be
used with different types of data
(objects).
This helps us to reuse our code.

it is possible to create classes that work


with different data types.
An entity such as class, interface, or
method that operates on a parameterized
type is a generic entity.
Advantages of Java Generics
1. Code Reusability
2. Compile-time Type Checking
3. Used with Collections
1. Code Reusability
With the help of generics in Java, we can write
code that will work with different types of data.
Example:
public <T> void genericsMethod(T data)
{...}
Here, we have created a generics method. This
same method can be used to perform
operations on integer data, string data, and so
on.
2. Compile-time Type Checking
The type parameter of generics provides
information about the type of data used in the
generics code.
Example:// using Generics
GenericsClass<Integer>list=new
GenericsClass<>();
Here, we know that GenericsClass is working
with Integer data only.
Now, if we try to pass data other than Integer
to this class, the program will generate an error
at compile time.
3. Used with Collections
The collections framework uses the concept of
generics in Java.
Example:// creating a string type ArrayList
ArrayList<String> list1 = new
ArrayList<>();
// creating a integer type ArrayList
ArrayList<Integer> list2 = new
ArrayList<>();
We have used the same ArrayList class to work
with different types of data.
Similar to ArrayList, other collections
(LinkedList, Queue, Maps, and so on)

1.Generic Classes
2.Generic Methods
3.Bounded types
1.Generic Classes:
1.A generic class is implemented exactly like
a non-generic class.
2.The only difference is that it contains a
type parameter section.
3.There can be more than one type of
parameter, separated by a comma.
4.The classes, which accept one or more
parameters, These are known as
parameterized classes or parameterized
types

Generic Class

Like C++, we use <> to specify parameter


types in generic class creation.
To create objects of a generic class, we use the
following syntax.
// To create an instance of generic class
BaseType <Type> obj = new BaseType
<Type>()
Note: In Parameter type we can not use
primitives like ‘int’,’char’ or ‘double’.
class Test<T>
{
T obj;
Test(T obj)
{
this.obj = obj;
}
public T getObject() { return
this.obj; }
}
class Main
{
public static void main(String[] args)
{
Test<Integer> iObj = new
Test<Integer>(15);
System.out.println(iObj.getObject());
Test<String> sObj = new
Test<String>("Generic Class");
System.out.println(sObj.getObject());
}}
Output: 15
Generic Class

Generic Methods:

It can be called with different types of


arguments based on the types of arguments
passed to the generic method.
Example:
class Test
{
static <T> void genericDisplay(T element)
{
System.out.println(element.getClass().getNam
e()+"="+element);
}
public static void main(String[] args)
{
genericDisplay(11);
genericDisplay("Generic Method");
genericDisplay(1.0);
genericDisplay(1024.237586854545444);
}
}
Output:
java.lang.Integer=11
java.lang.String=Generic Method
java.lang.Double=1.0
java.lang.Double=1024.2375868545455

Bounded Type:

we want to restrict the types that can be used


as type arguments in a parameterized type. For
example, a method that operates on numbers
might only want to accept instances of Number or
its subclasses. This is what bounded type
parameters are for.
Here is the syntax for declaring Bounded type
parameters.
<T extends SuperClass>
This specifies that ‘T’ can only be replaced by
‘SuperClass’ or it subclasses. Remember that
extends clause is an inclusive bound. That means
bound includes ‘SuperClass’ also.
Example: <T extends Number>
Note that, in this context, extends is used in a
general sense to mean either "extends" (as in
classes) or "implements" (as in interfaces).
Example:
class Bound<T extends A & B>
{
private T obr;
public Bound(T obj)
{
this.obr = obj;
}
public void runtest()
{
this.obr.displayClass();
}
}
interface B
{
public void displayClass();
}
class A implements B
{
public void displayClass()
{
System.out.println("Inside super class A");
}
}
class BoundedClass
{
public static void main(String a[])
{
Bound<A> b = new Bound<A>(new
A());
b.runtest();
}
}
Output: Inside super class A

Java Programming_Unit 4_Day


_MCQ_Generics
Q1.Why are generics used?
1.Generics make code more optimized and
readable.
2.Generics add stability to your code by
making more of your bugs detectable at
compile time.
3.Generics add stability to your code by
making more of your bugs detectable at
runtime.
4.Generics make code faster.
Q2. Which of these type parameters is used
for a generic class to return and accept any
type of object?
K
V
N
T
Q3. Which of these type parameters is used
for a generic class to return and accept a
number?
K
V
N
T
Q4. Which of these is the correct way of
defining generic class?
class name(T1, T2, …, Tn) { /* … */ }
class name{T1, T2, …, Tn} { /* … */ }
class name<T1, T2, …, Tn> { /* … */ }
class name[T1, T2, …, Tn] { /* … */ }
Q5. Which of the following is an incorrect
statement regarding the use of generics and
parameterized types in Java?
1.Generics provide type safety by
shifting more type-checking
responsibilities to the compiler.
2.When designing your own collections
class (say, a linked list), generics and
parameterized types allow you to
achieve type safety with just a single
class definition as opposed to defining
multiple classes.
3.Generics and parameterized types
eliminate the need for down casts
when using Java Collections.
4.All of the mentioned.
Q6. Which of the following reference types
cannot be generic?
Interface
Anonymous inner class
Inner class
All of the mentioned
Q7. Suppose a Generic class called
SortObjects is to be made capable of sorting
objects of any type(integer, single, byte, etc).
Then, which of the following programming
constructs is able to implement the comparison
function?
interface
delegate
encapsulation
attribute
Q8.Which of these data types cannot be type
parameterized?
Array
Set
Map
List
Q9. What is the output of this program?

Compilation error
Runtime error

obj478962

44

Q10. What will be the output of the following


Java program?

[1]

[0]

1
Answer Key & Solution
Q1 Generics add stability to your code by
making more of your bugs detectable at
compile time.
Q2 T
Q3 N
Q4 class name<T1, T2, …, Tn> { /* … */ }
Q5 When designing your own collections class
(say, a linked list), generics and parameterized
types allow you to achieve type safety with just
a single class definition as opposed to defining
multiple classes.
Q6 Anonymous inner class
Q7 delegate
Q8 Array
Q9 44
Q10 [0]

Collection frameworks
Overview– Collection Interfaces – Collection
Classes.
Collection:
The Collection in Java is a framework that provides
an architecture to store and manipulate the group
of objects.
Java Collection is a predefined architecture
capable of storing a group of elements and
behaving like a single unit such as an object or a
group.

Java Collections can achieve all the operations that


you perform on data such as searching, sorting,
insertion, manipulation, and deletion.

Java Collection means a single unit of objects. The


Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).
Framework:
It provides readymade architecture.
It represents a set of classes and interfaces.
It is optional.
The Collection framework represents a unified
architecture for storing and manipulating a group
of objects.
Interfaces and its implementations, i.e., classes
Algorithm
Hierarchy of Collection Framework
Let us see the hierarchy of the Collection
framework. The java.util package contains all the
classes and interfaces for the Collection
framework.
Methods of Collection interface
There are many methods declared in the Collection
interface. They are as follows:

N Method Description
o
.

1 public boolean add(E e) It is used to insert an element in


this collection.

2 public boolean It is used to insert the specified


addAll(Collection<? extends collection elements in the invoking
E> c) collection.

3 public boolean It is used to delete an element


remove(Object element) from the collection.

4 public boolean It is used to delete all the elements


removeAll(Collection<?> c) of the specified collection from the
invoking collection.

5 default boolean It is used to delete all the elements


removeIf(Predicate<? super of the collection that satisfy the
E> filter) specified predicate.
6 public boolean It is used to delete all the elements
retainAll(Collection<?> c) of invoking collection except the
specified collection.

7 public int size() It returns the total number of


elements in the collection.

8 public void clear() It removes the total number of


elements from the collection.

9 public boolean It is used to search an element.


contains(Object element)

10 public boolean It is used to search the specified


containsAll(Collection<?> c) collection in the collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] It converts collection into array.


a) Here, the runtime type of the
returned array is that of the
specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel


parallelStream() Stream with the collection as its
source.

16 default Stream<E> It returns a sequential Stream with


stream() the collection as its source.

17 default Spliterator<E> It generates a Spliterator over the


spliterator() specified elements in the
collection.

18 public boolean It matches two collections.


equals(Object element)

19 public int hashCode() It returns the hash code number of


the collection.

Iterator interface

Iterator interface provides the facility of iterating


the elements in a forward direction only.

Methods of Iterator interface


No Method Description
.

1 public It returns true if the iterator has


boolean more elements otherwise it
hasNext() returns false.

2 public It returns the element and


Object moves the cursor pointer to the
next() next element.

3 public void It removes the last elements


remove() returned by the iterator. It is
less used.

Collection interface methods

1. Iterable Interface
2. Collection Interface
3. List Interface
4. ArrayList
5. LinkedList
6. Vector
7. Stack
8. Queue Interface
8.1 PriorityQueue
8.2 Deque Interface
8.3 ArrayDeque
9. Set Interface
10. HashSet
11. LinkedHashSet
12. SortedSet Interface
13. TreeSet

1. 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.

Iterator<T> iterator()

It returns the iterator over the elements of type T.

2. Collection Interface
It is implemented by all the classes in the collection
framework.

It declares the methods that every collection will


have. In other words, this 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.

3. 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.
1. List <data-type> list1= new ArrayList();
2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new 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.

4. 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.

import java.util.*;
class TestJavaCollection1{

public static void main(String args[]){

ArrayList<String> list=new
ArrayList<String>();//Creating arraylist

list.add("Ravi");//Adding object in arraylist

list.add("Vijay");

list.add("Ravi");

list.add("Ajay");

//Traversing list through Iterator

Iterator itr=list.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

}
Output:

Ravi

Vijay

Ravi

Ajay

5. 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.

import java.util.*;

public class TestJavaCollection2{

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

6. 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.

Consider the following example.

import java.util.*;

public class TestJavaCollection3{

public static void main(String args[]){

Vector<String> v=new Vector<String>();

v.add("Ayush");

v.add("Amit");

v.add("Ashish");

v.add("Garima");
Iterator<String> itr=v.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

Output:

Ayush

Amit

Ashish

Garima

7. 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.

import java.util.*;

public class TestJavaCollection4{

public static void main(String args[]){

Stack<String> stack = new


Stack<String>();

stack.push("Ayush");

stack.push("Garvit");

stack.push("Amit");

stack.push("Ashish");

stack.push("Garima");

stack.pop();

Iterator<String> itr=stack.iterator();

while(itr.hasNext()){
System.out.println(itr.next());

Output:

Ayush

Garvit

Amit

Ashish

8. 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.
Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the


Queue interface, some of them are given below.

8.1 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.

import java.util.*;

public class TestJavaCollection5{

public static void main(String args[]){

PriorityQueue<String> queue=new
PriorityQueue<String>();

queue.add("Amit Sharma");
queue.add("Vijay Raj");

queue.add("JaiShankar");

queue.add("Raj");

System.out.println("head:"+queue.element());

System.out.println("head:"+queue.peek());

System.out.println("iterating the queue


elements:");

Iterator itr=queue.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

queue.remove();

queue.poll();

System.out.println("after removing two


elements:");
Iterator<String> itr2=queue.iterator();

while(itr2.hasNext()){

System.out.println(itr2.next());

Output:

head:Amit Sharma

head:Amit Sharma

iterating the queue elements:

Amit Sharma

Raj

JaiShankar

Vijay Raj

after removing two elements:


Raj

Vijay Raj

8.2 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. Deque d = new ArrayDeque();

8.3 ArrayDeque

ArrayDeque class implements the Deque interface.


It facilitates us to use the Deque. Unlike queue, we
can add or delete the elements from both the ends.

ArrayDeque is faster than ArrayList and Stack and


has no capacity restrictions.

Consider the following example.

import java.util.*;
public class TestJavaCollection6{

public static void main(String[] args) {

//Creating Deque and adding elements

Deque<String> deque = new


ArrayDeque<String>();

deque.add("Gautam");

deque.add("Karan");

deque.add("Ajay");

//Traversing elements

for (String str : deque) {

System.out.println(str);

Output:
Gautam

Karan

Ajay

9. 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.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-


type>();
2. Set<data-type> s2 = new
LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-
type>();
10. HashSet

HashSet class implements Set Interface. It


represents the collection that uses a hash table for
storage. Hashing is used to store the elements in
the HashSet. It contains unique items.

Consider the following example.

import java.util.*;

public class TestJavaCollection7{

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());

Output:

Vijay

Ravi

Ajay

11. 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.

Consider the following example.

import java.util.*;

public class TestJavaCollection8{

public static void main(String args[]){

LinkedHashSet<String> set=new
LinkedHashSet<String>();

set.add("Ravi");

set.add("Vijay");

set.add("Ravi");

set.add("Ajay");

Iterator<String> itr=set.iterator();

while(itr.hasNext()){

System.out.println(itr.next());
}

Output:

Ravi

Vijay

Ajay

12. 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 additional methods that inhibit the natural
ordering of the elements.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();


13. TreeSet

Java TreeSet class implements the Set interface


that uses a tree for storage. Like HashSet, TreeSet
also contains unique elements. However, the
access and retrieval time of TreeSet is quite fast.
The elements in TreeSet stored in ascending order.

Consider the following example:

import java.util.*;

public class TestJavaCollection9{

public static void main(String args[]){

//Creating and adding elements

TreeSet<String> set=new
TreeSet<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());

Output:

Ajay

Ravi

Vijay
MCQ
Q1. What is Collection in Java?

Group of Classes

Group of Objects

Group of Interfaces

All of the mentioned


Q2. Which of these classes is not part of Java’s
collection framework?

Maps

Array

Stack
Queue
Q3. Which of the following is used to find the
maximum value present in the List?

Collections.max()

Collections.largest()

Collections.maximum()

None
Q4. Which of the following will be used to remove
the element from the List while iterating?

for loop

for each loop

iterator

entrySet
Q5. What will be the output of the following code
snippet?
ArrayList al = new ArrayList();
al.add(30);
al.add(20);
al.add(10);
al.add(40);
al.add(50);
Collections.sort(al, Collections.reverseOrder());
System.out.println(al);
[10,20,30,40,50]

[50,40,10,20,30]

[50,40,30,20,10]

None
Q6. Which cannot fill in the blank for this code to
compile?
Collection < String > c = new ____________< >();
c.add(" pen"); c.remove(" pen");
System.out.println( c.isEmpty());
ArrayDeque

TreeMap

TreeSet

All of these can fill in the blank.


Q7. Which of these packages contain all the
collection classes?

java.lang

java.util
java.net

java.awt
Q8. List, Set and Queue __________ Collection.

extends

implements

both of the above

none of the above


Q9. Which statement is true for the class
java.util.ArrayList?

The elements in the collection are ordered.

The collection is guaranteed to be immutable.

The elements in the collection are guaranteed


to be unique.

The elements in the collection are accessed


using a unique key.
Q10. What is the result of the following?
ArrayList < Integer > list = new ArrayList < >();
list.add( 56); list.add( 56);
list.add( 3);
TreeSet < Integer > set = new TreeSet < >( list);
System.out.print( set.size());
System.out.print(" " );
System.out.print( set.iterator(). next());
23

2 56

33

3 56
Answer Key & Solution
Section 1 - MCQ
Q1 Group of Objects
Q2 Maps
Q3 Collections.max()
Q4 iterator
Q5 [50,40,30,20,10]
Q6 TreeMap
Q7 java.util
Q8extends SolutionList, Set and Queue are all
interfaces and they extends Collection interface.
(interface extends interface)
Q9The elements in the collection are ordered.
SolutionYes, always the elements in the collection

are ordered.

Q10 2 3

You might also like