Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Java 3rd Unit

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

UNIT-3

I/O STREAMS AND COLLECTIONS


3.1 - LIST DIFFERENT TYPES OF 1/O STREAMS :
• Java 1/ (Input and Output) is used to process the input and produce the output.
• Java uses the concept of a stream to make 1/0 operation fast.
• 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. It's called a stream because it is like a stream of
water that continues to flow.
• In Java, 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
Let's see the code to print output and an error message to the console.
1. System.out.println("simple message");
2. System. err. printin("error message");
Let's see the code to get input from console.
1. Inti=System.in.read();//returns ASCIl code of 1st character.
2. System.out.println((char)i);//will print the character.
OutputStream vs InputStream :
OutputStream :
Java application uses an output stream to write data to a destination; it may be a file, an
array ,peripheral device or socket.
InputStream :
Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given
below.

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

3.2 - EXPLAIN HOW TO READ AND WRITE DATA THROUGH CONSOLEINPUT AND
OUTPUT STREAMS AND WRITE A SAMPLE PROGRAM :
Ways to read input from console in Java: In Java, there are four different ways for
reading input from the user in the command line environment (console).
1. Using Buffered Reader Class: This is the Java classical method to take input, introduced
in JDK1.0. This method is used by wrapping the System.in (standard input stream) in an
InputStreamReader which is wrapped in a BufferedReader, we can read input from the
user in the command line.
• The input is buffered for efficient reading.
• The wrapping code is hard to remember.
Implementation:
// Java program to demonstrate BufferedReader
import java. io. BufferedReader;
import java. io. IOException;
import java. io. InputStreamReader;
public class Test{
public static void main (String[args) throws IOException{
// enter data using BufferedReader
BufferedReader reader = new BufferedReader (new
InputStreamReader (System. in) ) ;
// Reading data using readLine
String name = reader. readLine () ;
// Printing the read line
System. out. println (name) ;
(A.")
}
}
Input: Kiran
Output: Kiran
Note: To read other types, we use functions like Integer. parselnt),
Double.parseDouble(). To read multiple values, we use split ).
2. Using Scanner Class: This is probably the most preferred method to take input. The
main purpose of the Scanner class is to parse primitive types and strings using regular
expressions, however, it is also can be used to read input from the user in the command
line.
• Convenient methods for parsing primitives (nextInt), nextFloat (), ...) from the
tokenized input.
• Regular expressions can be used to find tokens.
• The reading methods are not synchronized.
// Java program to demonstrate working of Scanner in Java
importjava.util. Scanner; class Get InputFromUser l
public static void main (String args [])
// Using Scanner for Getting Input from User
Scanner in = new Scanner (System. in) ;
String s = in. nextLine ();
System. out. println ("You entered string " + s) ;
int a = in. nextInt () ;
System. outprintin ("You entered integer " + a) ;
float b = in.nextFloat () ;
System. outprintln ("You entered float " + b) ;
}
}
Input:KiranForJava
12
3.4
Output: You entered string Kiran For Java
You entered integer 12
You entered float 3.4
3. Using Console Class: It has been becoming a preferred way for reading user's input
from the command line. In addition, it can be used for reading password-like input
without echoing the characters entered by the user; the format string syntax can also be
used (like System.out.printf()).
Advantages:
1. Reading password without echoing the entered characters.
2. Reading methods are synchronized.
3. Format string syntax can be used.
4. Does not work in non-interactive environment (such as in an IDE).
// Java program to demonstrate working of System. console ()
// Note that this program does not work on IDEs as System. console ()
may require console public class Sample
public static void main (Stringll args)
// Using Console to input data from user
String name = System. console () .readLine () ;
System. outprintln ("You entered string " + name) ;
Input: KiranForJava
Output: You entered string KiranForJava
4. Using Command line argument:
• This is most used user input for competitive coding.
• The command-line arguments are stored in the String format.
• The parselnt method of the Integer class converts string argument intoInteger. Similary
,for float & others during e xecution.
• The usage of args [] comes into existence in this input form.
• The passing of information takes place during the program run.
• The command line is given to args[] These programs have to be run on cmd.
Code: // Program to check for command line arguments
class Main {
public static void main (String(] args){
// check if length of args array is greater than 0
if (args. length › 0) {
System. out. println ("The command line arguments are:");
// iterating the args array and printing the command line
arguments
for (String val : args){
System. out. println (val) ;
}
else
System. outprintln ("No command line " + "arguments found.") ;
}
}
Command Line Arguments: java Main Hello World
Output:
The command line arguments are: Hello World
Ways to write output to console in Java: The following two methods are used to write
the output data to console in Java.
Method1: Writing with System.out.println
Ex: System.out.println ("Hello, world!");
Program output: Hello, world!
Method2: Writing with printf()
The printf(String format, Object... args) method takes an output string and multiple
parameters which are substituted in the given string to produce the formatted output
content. This formatted output is written in the console.
Ex: String name = "Lokesh";
int age = 38;
console. printf("My name is %s and my age is %d", name, age);
Program output : My name is Lokesh and my age is 38

3.3 - EXPLAIN HOW TO USE DATAINPUTSTREAM AND DATA OUTPUT STREAM TO


ACCESS PRIMITIVE DATA TYPES AND WRITE A SAMPLE PROGRAM:
DatalnputStream in Java :
• It reads bytes from an underlying stream and converts them into suitable primitive-type
values or strings.
• The basic input stream provides read methods only for reading bytes or characters. If
we want to read the primitive data types, we need to use a filter class DatalnputStream.
• DatalnputStream class works as wrappers on the existing input stream to filter data in
the original stream.
Java DatanputStream class declaration:
The general declaration for DatalnputStream class in Java is given below:
public class DatalnputStream extends FilterInputStream implements Datalnput.
Here DatalnputStream class extends FilterInputStream class that extends InputStream.
It implements the interface Datalput to use methods defined in the Datalnput interface.
Constructor of DatanputStream class in Java.
DatalnputStream class defines only a single constructor in Java that is as follows.
DatalnputStream (InputStreaminputStream);
This constructor creates a DatalnputStream object that uses the specifit underlying
InputStream. Here, inputStream defines the input stream from which data will be read.
A data input stream object for input can be created as follows:
FileInputStreamfis = new FilenputStream (String filename);
DatalnputStream dis = new DatalnputStream (fis);
•These two statements basically wrap dis on fis and use it as a filter. Look at the figure
below.
DatanputStream Methods in Java:
In addition to methods inherited by InputStream and FilterInputStreamsuperclasses,
DatalnputStream class uses also methods defined by Datalput interface that make it
unique.
These methods read a sequence of bytes and convert them into values of primitive data
types.
A list of few important methods provided by Datalnput interface is as follows:
Methods Description
1.boolean readBoolean(): This method reads byte from the stream
and converts into boolean value. It returns
true if byte is non zero, false if byte is zero.
2.byte readByte() This method reads a single byte from
contained input stream and returns a
singed byte.
3.short readShort(): This method reads two bytes and returns a
short value.
4.char readChar(): It reads two bytes from the contained input
stream and returns a char value.
5.intreadInt(): It reads 4 bytes from contained input
stream and returns an Int value
6.long readLong(): This method read 8 bytes from the input
stream and
returns a long value.
7.float readFloat(): This method reads 4 bytes, converts data
into float
value, and returns it.
8.double readDouble(): The readDouble() method reads & bytes,
convertsdata into double value, and
returns it.
9.String readUTF(): This method reads the length of string and
thenreads and returns a string that has been
encoded using the UTF-8 format.

All these methods will throw an exception named lOException when any error
encounters.
Java DatalnputStream Example Program:
Let's take an example program where we will write primitive data types in a file, then
read data from the file, and display them on the screen. Look at the following source
code below.
Program:
packagejavaProgram;
import java.io. DataInputStream; import java. io. DataOutputStream; import java. io.
FileInputStream; import java. 10.FileOutputStream;
import java. io. IOException;
public class DataInputStreamEx 1{
public static void main (String[] args) throws IOException{
String filepath = "D: | \myfileoutdat" ;
// Create a FileOutputStream object to connect with myfileout. dat
file.
FileOutputStreamfos = new FileOutputStream (filepath) ;
// Create a DataOutputStream object to wrap on fos.
DataOutputStream dos = new DataOutputStream (fos) ;
// Write following primitive data to the "myfileoutdat" file.
doswriteUTF ("Welcome to Java world") ;
doswriteInt (1246) ;
dos. writeDouble (125.25) ; dos. writeBoolean (true) ;
doswriteChar ('S') ;
dos. close () ; fos. close () ;
// Reading data from the "myfileout.dat" file.
FileInputStreamfis = new FileInputStream (filepath) ;
DataInputStream dis = new DataInputStream (fis) ;
System. outprintin(dis.readUTE()) ;
System. out. println (dis.readInt ()) ;
System. out. printin (dis.readDouble ()) ;
System. outprintln(dis. readBoolean ()) ;
System. outprintln (dis.readChar ()) ;
dis. close () ;
fis. close () ;
}
}
Output:
Welcome to Java world
1246
125.25
true
S
In this program, we have performed reading and writing primitive data types by
wrapping DatalnputStream on FileInputStream.
The program first creates "myfileout.dat" file on the mentioned filepath and then writes
the string and primitive data types into it using data output stream.
At the end of writing, streams are closed using close() method.
DataOutputStream in Java | Methods, Example:
It enables us conveniently to write strings and all primitive data types such as boolean,
int, float, long, etc to a stream. Java DataOutput Stream first converts primitive-type
values or strings into bytes and then writes them to the underlying output stream in an
appropriate way. Using data input stream, we can then read the data back in. Thus,
DataOutputStream works as wrappers on the existing output stream to filter data in the
original stream.
Java DataOutputStream class declaration:
DataOutputStream class extends Filter Output Stream class that extends Output Stream. It
implements the interface Data Output to use methods defined in the Data Output
interface. The general declaration for Data Output Stream class in Java is given below:
public class Data Output Stream extends Filter Output Stream implements Data Output.
Constructor of DataOutputStream class:
DataOutputStream class defines only a single constructor in Java that is as
follows:
DataOutputStream (OutputStreamoutputStream):
This constructor creates a DataOutputStream object that uses the specifie underlying
Output Stream. Here, output Stream defines the output stream which data will be
written.
A data output stream object for output can be created as follows:
File Output Stream fos = new File Output Stream (String filename);
Data Output Stream dos = new DataOutputStream(fos);
These two statements basically wrap dos on fos and use it as a filter. Look at the figure
below.

To append data to an existing file, use the following syntax:


File OutputStreamfos = new FileOutputStream(String filename, true);
Data OutputStream dos = new DataOutputStream(fos);
Data OutputStream Methods in Java;
In addition to methods inherited by OutputStream and Filter OutputStreamsuperclasses,
Data OutputStream class uses also methods defined by Data Output interface that make it
unique. These methods convert values of a primitive data type into a byte sequence and
then writes it to the underlying stream.
A list of important methods provided by DataOutput interface is as follows:
Method Description
1.void This method writes a boolean to the output stream as a 1-
writeBoolean(boolean b): byte value.
2.void writeByte(int v): This method writes out a byte to the output stream as a 1-
byte value.
3. void writeBytes(String s): This method writes the lower byte of characters in a string
to the underlying output stream as a sequence of bytes.
4. void writeChar(char c): This method writes a character composed of 2 bytes to
the underlying output stream, high byte first.
5.void writeChars(String s): This method writes a sequence of characters in a strings to
the underlying output stream, 2 bytes per character.
6.void writeDouble(double This method writes a double value to the underlying
v): output stream.
7.void writeFloat(float v): This method writes a float value to the underlying output
stream.
8.void writelnt(int v): It writes an int value to the underlying output stream.
9.void writeLong(long v): This method writes a long value to the underlying output
stream.
10.void writeShort(int v): This method writes a short value to the underlying output
stream.
11.void writeUTF(String str): This method writes a string to the underlying output
stream using UTF-8 format.

All of these methods can throw an exception named lOException if any error occurs.
Java DataOutputStream Example Program:
Let's take a simple example program where we will perform reading and writing
operations using DatalnputStream and DataOutputStream. Look at the following source
code below.
Program code 1:
packagejavaProgram
import java.io. DataInputStream;
import java. io. DataOutputStream;
import java.io. FileInputStream;
import java. io. FileOutputStream;
import java. io. IOException;
public class DataOutputStreamEx 1{
public static void main (String[]args) throws IOException{
String filepath = "D: | \myfileout.dat";
Create a FileOutputStream object to connect with myfileout.datafile.
FileOutputStreamfos = new FileOutputStream (filepath) ;
// Create a DataOutputStream object to wrap on fos.
DataOutputStream dos = new DataOutputStream (fos) ;
// Write following primitive data to the "myfileout.dat" file.
doswriteUTF ("Welcome to Java World ") ; dos writeInt (124) :
doswriteDouble (125.25) ; dos. writeBoolean (true) ;
doswriteChar ('A');
dos. close () ; fos. close () :
// Read data from the "myfileout.dat" file.
File InputStreamfis = new File InputStream (filepath) ;
DataInputStream dis = new DataInputStream (fis) ;
System. outprintin (dis. readUTF () ) ;
System. outprintln(dis.readInt ()) ;
System. outprintin (dis.readDouble () ) ;
System.outprintln(dis.readBoolean ()) ;
System. outprintin(dis. readchar ()) ;
dis. close () ;
fis.close () ;
}
}
Output: Welcome to Java World
124
125.2
true
This program first creates "myfileout.dat" file on the mentioned filepath and then writes
the string and primitive data types into it using data output stream.
At the end of writing, streams are closed using close() method.
3.4 - EXPLAIN VARIOUS FILE ACCESS OPERATIONS BY USING FILE STREAMS AND
WRITE A SAMPLE PROGRAM:
• File Handling is an integral part of any programming language as file handling enables
us to store the output of any particular program in a file and allows us to perform certain
operations on it. In simple words, file handling means reading and writing data to a file.
• In Java, with the help of File Class, we can work with files.
• This File Class is inside the java.io package.
• The File class can be used by creating an object of the class and then specifying the
name of the file.
Java File Class Methods :
The following table depicts several File Class methods:
Method Name Description Return
Type
can Read() It tests whether the file is readable Boolean
or not.
can Write() It tests whether the file is writable Boolean
or not.
create New File() It creates an empty file. Boolean
delete() It deletes a file. Boolean
exists() It tests whether the file exists or Boolean
not.
length() Returns the size of the file in bytes. Long
getName() Returns the name of the file. String
list() Returns an array of the files in the String[]
directory.
mkdir() Creates a new directory. Boolean
get Absolute Path() Returns the absolute pathname of String
the file.
File operations in Java:
The following are the several operations that can be performed on a file in Java :
Create a File
Read from a File
Write to a File
Delete a File
Now let us study each of the above operations in detail.
1. Create a File
In order to create a file in Java, you can use the createNewFile ) method.
If the file is successfully created, it will return a Boolean value true and false if the file
already exists.
Example program:
// Import the File class
import java.io. File;
// Import the IOException class to handle errors
import java. io. IOException;
public class KfJ {
public static void main (String[] args){
try {
File Obj = new File ("myfile.txt") ;
if (Obj. createNewFile ()) l
System. outprintin ("File created: "+ Obj. getName ()) ;
}
else {
System. out. println ("File already exists.") ;
}
catch (IOException e) {
System. outprintln ("An error has occurred.") ;
}
}
}
Output:
File created:myfile
2. Read from a File: We will use the Scanner class in order to read contents from a file.
Following is a demonstration of how to read contents from a file in Java :
// Import the File class
import java.io. File;
// Import this class for handling errors
import java. io. FileNotFoundException;
// Import the Scanner class to read content from text files
import java. util. Scanner;
public class KfJ {
public static void main (String[l args)
try {
File Obj = new File ("myfile.txt");
Scanner Reader = new Scanner (Obj ) ;
while (Reader. hasNextLine ()) {
String data = Reader. nextLine () ;
System. out. println (data) ;}
Reader. close () ;}
catch (FileNotFoundException e) {
System. outprintin ("An error has occurred.") ;
}
}
}
Output:
This is java programming

3. Write to a File: We use the FileWriter class along with its write() method in order to
write some text to the file.
Following is a demonstration of how to write text to a file in Java :
// Import the FileWriter class
import java.io. FileWriter;
// Import the IOException class for handling errors
import java. io. IOException;
public class Kfj{
public static void main (String [] args){
try {
FileWriter Writer= new FileWriter ("myfile. txt") ;
Writer. write ("Files in Java are seriously good!!");
Writer. close () ;
System. outprintin ("Successfully written.");
catch (IOException e) {
System. out. printin ("An error has occurred.") ;
}
}
}
Output:
Successfully written.
4. Delete a File: We use the delete ) method in order to delete a file.
Following is a demonstration of how to delete a file in Java :
// Import the File class
import java.io. File;
public class KEJ {
public static void main (String[]args)
{
File Obj = new File ("myfile.txt") ;
if (Obj. delete ()) {
System. out.printIn("The deleted file is : "+ Obj. getName ()) ;}
else {
System.out.printin ("Failed in deleting the file."); }
}
}
Output:
The deleted file is :myfile
3.5- WHAT IS A COLLECTION FRAMEWORK AND HIERARCHY OF COLLECTION
FRAMEWORK AND WRITE A SAMPLE PROGRAM:
The Collection in Java is a framework that provides architecture to store and manipulate
the group of objects, i.e. Java Collection means a single unit of objects i.e., a group.
• Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
• Collection framework has :
1. Interfaces and its implementations, i.e., classes
2. Algorithm
• Java Collection framework provides many interfaces (Set, List, Queue, Deque) and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Hierarchy of Collection Framework:
Let us see the hierarchy of Collectionframework. The java, util package contains all the
classes and interfaces for the collection framework.
3.6 LIST INTERFACE:
->List is an interface which can store multiple values of a
singledata type
->this is used to store multiple values under a single variable by implementing the list

ARRAY LIST:
->In java array list class provides resizable array and implements the list Interface.
->It implements all list operations and it also permits all elements including null
NOTE :The array list has default size of ‘0’ and capacity ‘10’ if the size of elements in
array list is more than the capacity, the capacity will be doubled.

Program:
importjava.util.*;
classArrayListDemo {
public static void main(String[] args) {
ArrayList<String> v = new ArrayList<>();
v.add("a");
v.add("b");
v.add("c");
System.out.println(v);
ArrayList<String> v1 = new ArrayList<>();
v1.add("d");
System.out.println(v1);
v1.addAll(v);
System.out.println(v1);
v1.removeAll(v);
System.out.println(v1);
v1.clear();
System.out.println(v1);
}
}
Output:
[a, b, c]
[d]
[d, a, b, c]
[d]
[]

LINKED LIST:
->The linked list lass extends abstract sequential list and implements the list interface.
->It has address and pointers that are used to link the elements and each element in the
linked list consist of two parts
1) Head: Thehead of the list refers to the first node address of the list.
2) Tail: Thetail of the list refers to the next node address of the list.

Program:
importjava.util.*;
public class LinkedListExample {
public static void main(String[] args) {
LinkedList<String> v = new LinkedList<>();
v.add("Apple");
v.add("Banana");
v.add("Orange");
v.add("Grapes");
System.out.println(v);
v.addFirst("Pineapple");
v.addLast("Mango");
System.out.println( v);
String firstElement = v.getFirst();
System.out.println("First Element: " + firstElement);
String lastElement = v.getLast();
System.out.println("Last Element: " + lastElement);
v.removeFirst();
v.removeLast();
System.out.println("LinkedList after removing first and last elements: " + v);
}
}
Output:
[Apple, Banana, Orange, Grapes][Pineapple, Apple, Banana, Orange, Grapes,
Mango]
First Element: Pineapple
Last Element: Mango
LinkedList after removing first and last elements: [Apple, Banana, Orange, Grapes]

Vector Class :
->The Vector class implements a grow able array of objects. Vectors fall in legacy
classes, but now it is fully compatible with collections. It is found in java.util
package and implement the List interface.
Program:
import java .util.*;
class vector{
public static void main(String [] args){
Vector <String> v1=new Vector<>();
System.out.println(v1);
System.out.println(v1.size());
System.out.println(v1.capacity());
v1.add("a");
v1.add("b");
v1.add("c");
System.out.println(v1);
System.out.println(v1.get(2));
System.out.println(v1.remove(1));
System.out.println(v1);
v1.clear();
System.out.println(v1)
}
}
Output:
[]
0
10
[a, b, c]
c
b
[a, c]
[]
STACK CLASS:
->It is a subclass of vector and it implements FIFO data structure.
->Stack contains all methods of vector class and also provide it’s methods.
Program:
import java .util.*;
class stack{
public static void main(String [] args){
Stack <String> v=new Stack<>();
v.push("a");
v.push("b");
v.push("c");
System.out.print(v.pop());
System.out.print(v.peek());
System.out.print(v.search("c"));
}
}
Output:
C b -1
QUEUE INTERFACE:
->Queue interface maintains FIFO order and it can be defined an ordered list

PRIORITY QUEUE:
->The priority queue class implements queue interface.
->It holds the elements or objects which are to be processed by their priorities, it does
not allow null values.
Program:
importjava.util.*;
classPriorityQueueExample {
public static void main(String[] args) {
PriorityQueue<Integer>pq = new PriorityQueue<>();
pq.offer(5);
pq.offer(2);
pq.offer(8);
pq.offer(1);
pq.offer(10);
System.out.println("PriorityQueue: " + pq);
while (!pq.isEmpty()) {
System.out.println("Removed: " + pq.poll());
}
}
}
Output:
PriorityQueue: [1, 2, 8, 5, 10]
Removed: 1
Removed: 2
Removed: 5Removed: 8
Removed: 10
ARRAY DEQUEUE:
->The interface called Deque is present in java.util package. It is the subtype of the
interface queue. The Deque supports the addition as well as the removal of elements
from both ends of the data structure.
-> the stack supports the Last In First Out (LIFO) operation, and the operation First In
First Out is supported by a queue.
Program:
importjava.util.*;
classArrayQueueExample {
public static void main(String[] args) {
ArrayDeque<Integer>pq = new ArrayDeque<>();
pq.offer(5);
pq.offer(2);
pq.offer(8);
pq.offer(1);
pq.offer(10);
System.out.println(pq);
System.out.println(pq.poll());
System.out.println(pq);
pq.pollFirst();
System.out.println(pq);
pq.pollLast();
System.out.println(pq);
System.out.println(pq.peek());
}
}
Output:
[5, 2, 8, 1, 10]
5
[2, 8, 1, 10]
[8, 1, 10]
[8, 1]
8
SET INTERFACE:
->It accepts unique elements only and it prints the data randomly.
->It is an unordered collection of objects in which duplicate values cannot be stored. It is
an interface that implements the mathematical set.

HASH SET:
->Java Hash Set class implements the Set interface, backed by a hash table which is
actually a Hash Map instance. No guarantee is made as to the iteration order of the hash
sets which means that the class does not guarantee the constant order of elements over
time.
Program:
importjava.util.*;
classHashMapExample {
public static void main(String[] args) {
HashSet<Integer> h = new HashSet<>();
h.add(5);
h.add(9);
h.add(7);
System.out.println(h);
for (Integer i : h) {
System.out.println(i);
}
}
}
Output:
[5, 7, 9]
5
7
9

LINKED HASH SET:


->Java Linked Hash Set class is a Hash table and Linked list implementation of the Set
interface. It inherits the Hash Set class and implements the Set interface.
Program:
importjava.util.*;
class Main {
public static void main(String[] args) {
LinkedHashSet<String> v = new LinkedHashSet<>();
v.add("Apple");
v.add("Banana");
v.add("Orange");
System.out.println( v);
v.remove("Banana");
System.out.println(v);
}
}
Output:
[Apple, Banana, Orange]
[Apple, Orange]

TREE SET:
-> Tree Set is one of the most important implementations of the Sorted Set interface in
Java that uses a Tree for storage. The ordering of the elements is maintained by a set
using their natural ordering whether or not an explicit comparator is provided.
Program:
importjava.util.*;
class h1 {
public static void main(String[] args) {
TreeSet<Integer>treeSet = new TreeSet<>();
treeSet.add(5);
treeSet.add(3);
treeSet.add(8);
treeSet.add(2);
System.out.println(treeSet);
treeSet.remove(3);
System.out.println(treeSet);
}
}
Output:
[2, 3, 5, 8]
[2, 5, 8]

MAP INTERFACE:
->In Java, Map Interface is present in java.util package represents a mapping between a
key and a value. Java Map interface is not a subtype of the Collection interface.
Therefore it behaves a bit differently from the rest of the collection types. A map
contains unique keys.
HASH TABLE:
-> The Hash class implements a hash table, which maps keys to values. Any non-null
object can be used as a key or as a value. To successfully store and retrieve objects from a
hash table, the objects used as keys must implement the hash Code method and the
equal’s method.
Program:
importjava.util.*;
classHashTableExample {
public static void main(String[] args) {
HashTable<String, Integer>ht = new HashTable<>();
hashMap.put("sai", 25);
hashMap.put("Alice", 30);
hashMap.put("Bob", 35);
System.out.println(hashMap);
hashMap.remove("Alice");
System.out.println(hashMap);
}
}
Output:
{Bob=35, Alice=30, sai=25}
{Bob=35, sai=25}

LINKED HASH MAP:


-> The Linked Hash Map Class is just like Hash Map with an additional feature of
maintaining an order of elements inserted into it. Hash Map provided the advantage of
quick insertion, search, and deletion but it never maintained the track and order of
insertion, which the Linked Hash Map provides where the elements can be accessed in
their insertion order.
Program:
importjava.util.*;
classlinkedMap {
public static void main(String[] args) {
LinkedHashMap<String, Integer>linkedMap = new LinkedHashMap<>();
linkedMap.put("Apple", 10);
linkedMap.put("Banana", 20);
linkedMap.put("Orange", 30);
System.out.println(linkedMap);
linkedMap.remove("Banana");
System.out.println(linkedMap);
}
}
Output:
{Apple=10, Banana=20, Orange=30}
{Apple=10, Orange=30}
TREE MAP:
-> The Tree Map in Java is used to implement Map interface and Navigable Map along
with the Abstract Map Class. The map is sorted according to the natural ordering of its
keys, or by a Comparator provided at map creation time, depending on which
constructor is used. This proves to be an efficient way of sorting and storing the key-
value pairs
Program:
importjava.util.*;
classTreeMapExample {
public static void main(String[] args) {
TreeMap<String, Integer>treeMap = new TreeMap<>();
treeMap.put("A", 1);
treeMap.put("B", 2);
treeMap.put("C", 3);
System.out.println(treeMap);
treeMap.remove("B");
System.out.println(treeMap);
}
}
Output:
{A=1, B=2, C=3}
{A=1, C=3}
3.7 EXPLAIN ITERATOR AND LIST ITERATOR INTERFACE METHODS AND WRITE A
SAMPLE PROGRAM.
• An Iterator is an interface in Java and we can traverse the elements of a list in a
forward direction whereas a Listiterator is an interface that extends the Iterator interface
and we can traverse the elements in both forward and backward directions.
• An Iterator can be used in these collection types like List, Set, and Queue whereas
ListIterator can be used in List collection only.
• The important methods of Iterator interface are hasNext), next() and remove()
whereas important methods of Listlterator interface are add, hasNext), hasPrevious) and
removel).
Syntax for Iterator:
public interface Iterator < E>
Example program:
importjava.util. *;
public class IteratorTest {
public static void main (String[]args) {
List<String>listObject = new ArrayList<String> () ;
listObject add ("'India") ;
listObject. add ("Australia") ;
listObject. add ("England") ;
listObject. add ("Bangladesh") ;
listObject. add ("'South Africa") ;
Iterator it = listObject. iterator () ;
while (it.hasNext ()) {
System. out. println (it.next ()) }
}
}

Output :
India
Australia
England
Bangladesh
South Africa
Syntax for Listlterator:
public interface Listlterator<E> extends Iterator < E>
Example program:
importjava.util.*;
public class ListIteratorTest {
public static void main (String[] args) {
List<String>listObject = new ArrayList<String> () ;
listObject. add ("Java") ;
listObject. add ("Selenium") ;
listObject. add ("Python" ) ;
listObject. add ("Java Script") ;
listObject. add ("Cloud Computing") ;
ListIterator it = listobject. listIterator () ;
System. outprintln ("Iterating the elements in forward direction:");
while (it.hasNext ()) {
System. out. println (it.next () );
System. outprintln ("-----------------------------------------------------------------") ;
System. outprintln ("Iterating the elements in backward direction:");
while(it.hasPrevious()){
System. out. println (it. previous ()) ;
}
}
}
Output:
Iterating the elements in forward direction:
Java
Selenium
Python
Java Script
Cloud Computing
-----------------------------------------------------------------
Iterating the elements in backward direction:
Cloud Computing
Java Script
Python
Selenium
Java
3.10 - EXPLAIN ENUMSET & ENUMMAP CLASSES AND WRITE SAMPLE PROGRAM.
ENUMSET:
•The EnumSet is one of the specialized implementations of the Set interface for use with
theenumeration type. A few important features of EnumSet are as follows: It extends
AbstractSet class and implements Set Interface in Java.
PROGRAM:
importjava.util.*;
enum days{
Sunday,monday,tueday,wednesday
}
class h1{
public static void main(String []args){
Set <days> t=EnumSet.of(days.tueday,days.wednesday);
Iterator <days>i=t.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
Output:
tueday
wednesday
ENUMMAP:
•EnumMap is a specialized implementation of the Map interface for enumeration types.
It extends AbstractMap and implements the Map interface in Java. It belongs to java. util
package
PROGRAM:
Java EnumMap Example:
importjava.util.*;

classEnumMapExample {
// create an enum
publicenum Days {
Monday, Tuesday, Wednesday, Thursday
}

public static void main(String[] args) {


// create and populate enum map
EnumMap<Days, String> map = new EnumMap<Days, String>(Days.class);
map.put(Days.Monday, "1");
map.put(Days.Tuesday, "2");
map.put(Days.Wednesday, "3");
map.put(Days.Thursday, "4");

// print the map


for (Map.Entry m : map.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}
Output:
Monday 1
Tuesday 2
Wednesday 3
Thursday 4

You might also like