0% found this document useful (0 votes)
49 views

Java Unit-4 Student PPT-final

The document discusses lambda expressions in Java including syntax, functional interfaces, passing lambda expressions as arguments, and exceptions. It provides examples of lambda expressions with different parameters and block expressions. Lambda expressions allow for more concise implementation of interfaces.

Uploaded by

samsundar793
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Java Unit-4 Student PPT-final

The document discusses lambda expressions in Java including syntax, functional interfaces, passing lambda expressions as arguments, and exceptions. It provides examples of lambda expressions with different parameters and block expressions. Lambda expressions allow for more concise implementation of interfaces.

Uploaded by

samsundar793
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 123

22CS202

JAVA PROGRAMMING

UNIT IV
UNIT IV STRING HANDLING AND COLLECTIONS
SYLLABUS

• Lambda Expressions
• String Handling
• Collections
 The Collection Interfaces
 TheCollection Classes
• Iterator – Map
• Regular Expression Processing
What is lambda expression in Java?
• A lambda expression is a short block of code which takes in
parameters and returns a value.
• Lambda expressions are similar to methods, but they do not need a
name and they can be implemented right in the body of a method.
WITHOUT LAMBDA EXPRESSION WITH LAMBDA EXPRESSION

class ThreadImpl implements Runnable{ class ThreadExample{


public void run(){ public static void main(String[] args) {
Runnable r1=()->{
System.out.println("Thread1 is running...");
System.out.println("Thread1 is
} running...");

} };
Thread t1=new Thread(r1);
class ThreadExample{
t1.start();
public static void main(String[] args) {
}
ThreadImpl r1=new ThreadImpl(); }
Thread t1=new Thread(r1);
t1.start();
}
}
Advantage of Lambda Expression?
Reduced code size Where is Lambda Expression?
LAMBDA EXPRESSION
What is Lambda Expression?

• Lambda expressions are similar to methods and are a short block of code that takes

in parameters and returns a value.

• They are anonymous or unnamed method that does not execute on their own.

• it is used to implement a method defined by a functional interface.

• An interface which has only one abstract method is called functional interface.

• Java lambda expression is treated as a function, so compiler does not create .class

file.
LAMBDA EXPRESSION
Syntax
(argument-list) -> {body}

Java lambda expression is consisted of three components.


1) Argument-list: It can be empty or non-empty as well.
2) Arrow-token: It is used to link arguments-list and body of expression.
3) Body: It contains expressions and statements for lambda expression ( single line or block of
code).
No Parameter Syntax Single Parameter Syntax Multiple Parameter Syntax

() -> { (p1) -> { (p1,p2) -> {


//Body of no parameter lambda //Body of single parameter lambda //Body of multiple parameter lambda
} } }

The Parameter type can be implicit or it can be specified explicitly


LAMBDA EXPRESSION
Functional Interface

A functional interface is an interface that specifies only one abstract method.


Interface MyNumber
{
double getValue();
}
• the method getValue() is implicitly abstract, and it is the only method defined by MyNumber
• Thus, MyNumber is a functional interface,and its functionis defined by getValue()
• A lambda expression is not executed on its own
• It forms the implementation of the abstract method defined by the functional interface that specifies its target
type
LAMBDA EXPRESSION
Functional Interface

• When a lambda expression occurs in a target type context, an instance of a class is automatically created that

implements the functional interface, with the lambda expression defining the behavior of the abstract method

declared by the functional interface

• When that method is called through the target, the lambda expression is executed

• Inorder for a lambda expression to be used in a target type context, the type of the abstract method and the

type of the lambda expression must be compatible


Example 1 Output
import java.util.*;
interface MyNumber{ Fixed Value 123.45
Double getValue(); Random Value 78.4020074321781
}
Another Random Value 15.76123901
public class LB1 {
public static void main(String[] args) { MyNumber MyNum;
MyNum = () -> 123.45;
System.out.println("Fixed Value " + MyNum.getValue());
MyNum = () -> Math.random() * 100;
System.out.println("Random Value " + MyNum.getValue());
System.out.println("Another Random Value " + MyNum.getValue());
}
}
Example 2 30
interface Addable{ Output:
int add(int a,int b); 300
}

public class LambdaExpressionExample5{


public static void main(String[] args) {

// Multiple parameters in lambda expression


Addable ad1=(a,b)->(a+b);
System.out.println(ad1.add(10,20));

// Multiple parameters with data type in lambda expression


Addable ad2=(int a,int b)->(a+b);
System.out.println(ad2.add(100,200));
}
}
Example
Block Lambda Expression
interface NumericFunc {
• The right side of the lambda operator consists of a int func(intn);
}
block of code that can contain more than one
public class LB4{
Statement
• A block lambda is easy to create. Simply enclose the public static void main(String[] args) {
body within braces as you would any other block of NumericFunc factorial = (n) ->{
int result =1;
statements
for (int i = 1; i <= n; i++)
• we must explicitly use a return statement to return a
result = i *result;
value Return result;
};
System.out.println("The factorial is " +factorial.func(3));
The factorial is 6
Output: System.out.println("The factorial is " +factorial.func(5));

The factorial is 120 }


}
Generic Functional Interface
Example
• The functional interface can be generic (template). interface IValue<T> {
• In this case, the target type of the lambda expression is T GetValue();
determined based on the type specified in the reference to }

that functional interface. public class LB4{


public static void main(String[] args) {
IValue<Float> refIValue;
refIValue = () -> 3.1415f;
float v = refIValue.GetValue(); // v = 3.1415
System.out.println(“Generic ”+v);
refIValue = () -> "Hello world!"; // Error, the type is String and
not Float
}
Output: Generic 3.1415 }
Passing Lamda Expression as arguments
Example
interface MyFunc {
String func(String n}

public class Main {


static String myMethod(MyFunc sf, String s) {
return sf.func(s);
}

public static void main(String args[])


Output: {
String inStr = "This is a test";
String outStr;
THIS IS A TEST
System.out.println("Here is input string: " + inStr);

// Here, a simple expression lambda that uppercases a string


// is passed to myMethod().
outStr = myMethod((str) -> str.toUpperCase(), inStr);
System.out.println("The string in uppercase: " + outStr);
}
}
public class LB8{
Lambda Expression and Exception public static void main(String[] args) throwsEmptyArrayException
{
double[] values = { 1.0, 2.0, 3.0, 4.0 };
Example
DoubleNumericArrayFunc average = (n) ->{
interface DoubleNumericArrayFunc{
double sum =0;
double func(double[] n) throws EmptyArrayException; if (n.length ==0)
} throw new EmptyArrayException();
class EmptyArrayException extends Exception for (int i = 0; i < n.length;i++)
{ EmptyArrayException(){ sum += n[i];
super("ArrayEmpty"); return sum /n.length;
} };

} System.out.println("The average is " + average.func(values));


System.out.println("The average is " +average.func(new

Output: double[0]));
}
}

The average is 2.5


Exception in thread "main" EmptyArrayException: Array Empty
Lambda Expression and Variable Capture
• Variables defined by the enclosing scope of a lambda expression are accessible within the lambda expression.

• A lambda expression can use an instance or static variable defined by its enclosing class.

• A lambda expression can explicitly and implicitly access to this, which refers to the invoking instance of the lambda
expression's enclosing class.

• A lambda expression can get or set the value of an instance or static variable and call a method defined by its enclosing
class.

Variable Capture

• A variable capture happens when a lambda expression uses a local variable from its enclosing scope.

• In this case, a lambda expression may only use local variables that are effectively final.

• An effectively final variable is one whose value does not change after it is first assigned.

• There is no need to explicitly declare such a variable as final, although doing so would not be an error.
Example
interface MyFunc {
Note 1: int func(int n);
}
num++ is illegal because it attempts to modify
public class Main {
the value of num. public static void main(String args[])
{
Note 2: // A local variable that can be captured.
error, because it would remove the effectively int num = 10;

final status from num. MyFunc myLambda = (n) -> {


// This use of num is OK. It does not modify num.
int v = num + n;
If num were to be modified, either inside the
// num++; //Note 1
lambda or outside of it, num would lose its return v;
effectively final status. };
// num = 9; //Note 2
}
This would cause an error, and the program would
}
not compile.
STRING HANDLING
• String is a group of characters. They are objects of typeString.

• Once a String object is created it cannot be changed. Strings areImmutable.

• To get changeable strings use the class calledStringBuffer.

• String and StringBuffer classes are declared as final,so there cannot be sub classes of these classes.

Creating Strings:
There are two ways to create String object:
By string literal
By new keyword (Using constructors)
Example:
String str = "abc"; //Using literal
String str = new String(“abc”); //Using new keyword
String class Methods
1) The length() method returns the length of the string.
Eg: System.out.println("Varun".length()); // prints 5

The + operator is used to concatenate two or more strings.


Eg: String myName = "Varun";
String s = "My name is" + myName+ ".";

For string concatenation the Java compiler converts an operand to a String


whenever the other operand of the + is a String object.
String class Methods (Contd.).

• Characters in a string can be retrieved in a number of ways

public char charAt(int index)


– Method returns the character at the
specified index. An index ranges from 0 to length() - 1
char c;
c = "abc".charAt(1); // c = “b”
String class Methods (Contd.).

equals() Method- This method is used to compare the invoking String to the
object specified. It will return true, if the argument is not null and it is String
object which contains the same sequence of characters as the invoking String.

public boolean equals(Object anObject)

equalsIgnoreCase() Method- Compares this String to another String,


ignoring case considerations. Two strings are considered equal ignoring case if
they are of the same length, and corresponding characters in the two strings are
equal ignoring case.

public boolean equalsIgnoreCase(String


anotherString)
Strings created using assignment operator

• String s1 = “HELLO”;
• String s2 = “HELLO”;

HELLO
3e25ae

s1

3e25ae

s2
Comparing Strings using == operator
What is the output ?
public class StringTest{
public static void main(String[] args){
String s1="Hello";
String
s2="Hello";
if(s1==s2)
System.out.prin
tln("String
objects
referenced
are same");
} else
Output: String objects referenced
System.out.println("String are same
objects referenced
are not same");
}
Comparing Strings using equals method
What is the output ?
public class StringTest{
public static void main(String[] args){
String s1="Hello";
String s2="Hello";
if(s1.equals(s2))
System.out.print
ln("Strings are
equal");
else
System.out.print
ln("Strings are
not equal");
} Output: Strings are equal
}
23
Strings created using new keyword

• String s1 = new String(“HELLO”);


• String s2 = new String(“HELLO”);

HELLO
3e25ad

s1
HELLO
3e25ae

s2
Comparing Strings using == operator
What is the output ?
public class StringTest{
public static void main(String[] args){
String s1= new String("Hello");
String s2= new String("Hello");
if(s1==s2)
System.out.println("String objects
referenced
are same ");
else
System.out.println("String objects referenced
are not same");
} }
Output: String objects referenced are not same
Comparing Strings using equals method
What is the output ?
public class StringTest{
public static void main(String[] args){
String s1= new String("Hello");
String s2= new String("Hello");
if(s1.equals(s2))
System.out.println("Strings are
equal");
else
System.out.println("Strings are not
equal");
}
}
Output: Strings are equal
String class Methods

startsWith() – Tests if this string starts with the


specified prefix.
public boolean startsWith(String prefix)
"January".startsWith("Jan"); // true

endsWith() - Tests if this string ends with the


specified suffix.
public boolean endsWith(String suffix)
"January".endsWith("ry"); // true
String class Methods (Contd.).
• compareTo() - Compares two strings and to know which string is
bigger or smaller
– We will get a negative integer, if this String object is less
than the argument string
– We will get a positive integer if this String object is greater
than the argument string.
– We will get a return value 0(zero), if these strings are equal.

public int compareTo(String anotherString)


public int compareToIgnoreCase(String str)

This method is similar to compareTo() method but this does not take
the case of strings into consideration.
String class Methods (Contd.).

indexOf – Searches for the first occurrence of a character or


substring. Returns -1 if the character does not occur

public int indexOf(int ch)-

It searches for the character represented by ch within this string and returns the index of first
occurrence of this character

public int indexOf(String str) –

It searches for the substring specified by str within this string and returns the index of first
occurrence of this substring

String str = “How was your day today?”; str.indexof(‘t’);


str(“was”);
String class Methods (Contd.).

public int indexOf(int ch, int fromIndex)- It searches for the character represented by
ch within this string and returns the index of first occurrence of this character starting from the position
specified by fromIndex

public int indexOf(String str, int fromIndex) - Returns the index within this string of
the first occurrence of the specified substring, starting at the specified index.

String str = “How was your day today?”; str.indexof(‘a’, 6);


str(“was”, 2);
String class Methods (Contd.).

lastIndexOf() –It searches for the last occurrence of a particular character or substring

substring() - This method returns a new string which is actually a substring of this string.
It extracts characters starting from the specified index all the way till the end of the string
public String substring(int beginIndex)
Eg: "unhappy".substring(2) returns "happy"

public String substring(int beginIndex, int endIndex)

Eg: "smiles".substring(1, 5) returns "mile“


String class Methods (Contd.).

concat() - Concatenates the specified string to the end of this string

public String concat(String str)


"to".concat("get").concat("her") returns "together"
Example
String class Methods

• replace()- Returns a new string resulting from replacing all


occurrences of oldChar in this string with newChar
public String replace(char oldChar, char
newChar)

"wipra technalagies".replace('a', 'o')


returns "wipro technologies"

34
String class Methods (Contd.).

• trim() - Returns a copy of the string, with leading and trailing


whitespace omitted

public String trim()

String s = “ Hi Mom! “.trim();


S = “Hi Mom!”

• valueOf() – This method is used to convert a character array into String.


The result is a String representation of argument passed as character array

public static String valueOf(char[] data)


String class Methods (Contd.).

Other forms are:


public static String valueOf(char c)
public static String valueOf(boolean b)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
String class Methods (Contd.).

• toLowerCase(): Method converts all of the characters in a String to


lower case
• toUpperCase(): Method converts all of the characters in a String to
upper case

•public String toLowerCase() public String


toUpperCase()

• Eg: "HELLO WORLD".toLowerCase(); "hello


world".toUpperCase();
StringBuffer

• StringBuffer class objects are mutable, so they can be modified

• The length and content of the StringBuffer sequence can be changed


through certain method calls

• StringBuffer class defines three constructors:

– StringBuffer()//empty object
– StringBuffer(int capacity)//creates an empty object with a capacity
for storing a string
– StringBuffer(String str)//create StringBuffer object by using a string

38
String Buffer Operations
• StringBuffer has two main operations methods – append and insert

• Both these methods are overloaded so that they can accept


any type of data

Here are few append methods:


StringBuffer append(String str)
StringBuffer append(int num)

• As the name suggests, the append method adds the specified


characters at the end of the StringBuffer object
StringBuffer Operations (Contd.).
• The insert methods are used to insert characters at
the specified index location

Here are few insert methods:


StringBuffer insert(int index, String str)
StringBuffer append(int index, char ch)

• Index specifies at which point the string will be inserted into the
invoking StringBuffer object
• delete() - This method is used to delete specified
substring within the StringBuffer object

public StringBuffer delete(int start, int end)

40
StringBuffer Operations (Contd.).
replace() - This method is used to replace part of this StringBuffer(substring)
with another substring

public StringBuffer replace(int start, int end, String


str)

substring() - This method returns a new string which is actually a substring


of this StringBuffer. It extracts characters starting from the specified index
all the way till the end of the StringBuffer

public String substring(int start)


41
StringBuffer Operations (Contd.).

• reverse() - As the name suggests, sequence the character


is reversed with this method
public StringBuffer reverse()

• length() – Used to find the length of the StringBuffer

public int length()

42
Example

class FullName{
public static void main(String[] args)
{ StringBuffer sb=new StringBuffer();
String surname="Mallapudi";
String lastname="vijaya";
sb.append(surname);
System.out.println("Name: "+sb);
int n=surname.length();
sb.insert(n,lastname);
System.out.println("Full name:
"+sb);
System.out.println("In reverse =
"+sb.reverse());
43 }
StringBuffer Operations (Contd.).
• capacity() – We can find the capacity of the
StringBuffer using this method
•What is capacity ?
• The capacity is the amount of storage available for the characters
that have just been inserted
•public int capacity()

•charAt() - Used to find the character at a particular index


• position
•public char charAt(int index)

44 © 2012 WIPRO LTD | WWW.WIPRO.COM | CONFIDENTIAL


Quiz
What is the output ?
class StringExample {
public static void main(String[] args)
{ String st = new String("Wipro
Technologies");
String result1
StringBuffer sb == new
st.substring(6,12);
StringBuffer("Wipro
Technologies");
String result2 = sb.substring(6);
String result3 = sb.substring(6,12);
System.out.println("Substring of String st : "+result1);
System.out.println("Substring of StringBuffer sb (with
single argument): "+result2);
System.out.println("Substring of StringBuffer sb (with two
arguments) : "+result3); }
}
Substring of String st : Techno
Substring of StringBuffer sb (with single argument): Technologies
Substring of StringBuffer sb (with two arguments) : Techno
45 © 2012 WIPRO LTD | WWW.WIPRO.COM | CONFIDENTIAL
COLLECTIONS
• The Collection in Java is a framework that provides an architecture to
store and manipulate the group of objects.

• Collection is an interface in the java.util package that is used to define a


group, or collection of objects.

• Java Collections can achieve all the operations that you perform on a
data such as searching, sorting, insertion, manipulation, and deletion.

• Collections framework provide a set of standard utility classes to manage


collections.
The Collection Interfaces
• The Collections Framework defines several core interfaces
The Collection Classes
• The Collections Framework defines several core classes
Hierarchy of the Collection Framework
The Collection Interface
• The Collection interface is the foundation upon which the Collections
Framework is built because it must be implemented by any class that
defines a collection.

• Collection is a generic interface that has this declaration:

interface Collection<E>

• Here, E specifies the type of objects that the collection will hold.

• Collection extends the Iterable interface. This means that all collections
can be cycled through by use of the foreach style for loop.
The Methods Declared by Collection Interface:
The Methods Declared by Collection Interface:
The List Interface
• The Collection interface is the foundation upon which the Collections
Framework is built because it must be implemented by any class that
defines a collection.

• Collection is a generic interface that has this declaration:

interface Collection<E>

• Here, E specifies the type of objects that the collection will hold.

• Collection extends the Iterable interface. This means that all collections
can be cycled through by use of the foreach style for loop.
The Methods Declared by List Interface:
The ArrayList Class
• The ArrayList class extends AbstractList and implements the List interface.

• ArrayList supports dynamic arrays that can grow as needed.

• Standard arrays are of fixed size. After arrays are created they cannot grow
or shrink.

• It provides more powerful insertion and search mechanisms than arrays.

• Gives faster Iteration and fast random access.

• Ordered Collection (by index), but not Sorted.


ArrayList has the constructors shown here:

ArrayList( )
• Builds an empty array list.

ArrayList(Collection<? extends E> c)


• Builds an array list that is initialized with the elements of the collection c.

ArrayList(int capacity)
• Builds an array list that has the specified initial capacity.
• The capacity is the size of the underlying array that is used to store the elements.
• The capacity grows automatically as elements are added to an array list.
Example: System.out.println("Size of list after additions: " + list.size());
import java.util.*; // Display the array list.
class ArrayListDemo { System.out.println("Contents of list: " + list);
public static void main(String args[]) { // Remove elements from the array list.
// Create an array list. list.remove("F");
ArrayList<String> list = new ArrayList<String>(); list.remove(2);
System.out.println("Initial size of list: " + list.size()); System.out.println("Size of list after deletions: " + list.size());
// Add elements to the array list. System.out.println("Contents of list: " + list);
list.add("A"); }
list.add("C"); }
list.add("D"); Output:
list.add("E"); Initial size of list: 0
list.add("F"); Size of list after additions: 7
list.add("G"); Contents of list: [A, B, C, D, E, F, G]
list.add(1, "B"); Size of list after deletions: 5
Contents of list: [A, B, D, E, G]
Obtaining an Array from an ArrayList

• To convert a collection into an array, use toArray( ) method.

• There are two versions of toArray( ).


1. object[ ] toArray( ) - returns an array of Object

2. <T> T[ ] toArray(T array[ ]) - returns an array of elements that have the


same type as T.
Example: System.out.println("Contents of list: " + list);
// Convert an ArrayList into an array. // Get the array.
import java.util.*; int n=list.size();
class ArrayListToArray { Integer arr[] = new Integer[n];
public static void main(String args[]) { arr = list.toArray(arr);
// Create an array list. int sum = 0;
ArrayList<Integer> list = new ArrayList<Integer>(); // Sum the array.
// Add elements to the array list. for (int i : arr)
list.add(1); sum += i;
list.add(2); System.out.println("Sum is: " + sum);
list.add(3); }
list.add(4); }
Output:
Contents of list: [1, 2, 3, 4]
Sum is: 10
The LinkedList Class
• The LinkedList class extends AbstractSequentialList and implements the
List,Deque, and Queue interfaces.

• It provides a linked-list data structure.

• LinkedList has the two constructors shown here:

• LinkedList( )
• Builds an empty linked list.

• LinkedList(Collection<? extends E> c)


• Builds a linked list that is initialized with the elements of the collection c.
// Remove elements from the linked list.
Example:
ob.remove("F");
import java.util.*;
ob.remove(2);
class Main {
System.out.println("Contents of linked list after deletion: " + ob);
public static void main(String args[]) {
//Remove first and last elements.
// Create a linked list.
ob.removeFirst();
LinkedList<String> ob =new LinkedList<String>();
ob.removeLast();
// Add elements to the linked list.
System.out.println("Linkedlist after deleting first and last: " + ob);
ob.add("B");
//Get and set a value.
ob.add("C");
String val = ob.get(2);
ob.add("D");
ob.set(2, val + " Changed");
ob.add("E");
System.out.println("Linked list after change: " + ob);
ob.add("F");
}}
ob.addLast("G");
Output:
ob.addFirst("A");
Original contents of Linkedlist: [A, A1, B, C, D, E, F, G]
ob.add(1, "A1");
Contents of linked list after deletion: [A, A1, C, D, E, G]
System.out.println("Original contents of Linkedlist: " + ob);
Linkedlist after deleting first and last: [A1, C, D, E]
Linked list after change: [A1, C, D Changed, E]
The Stack Class
• Stack is a class that falls under the Collection framework that extends the Vector class.
Stack Class Constructor
The Stack class contains only the default constructor that creates an empty stack.
public Stack()
Creating a Stack
• Import the java.util package
• Create an object of the Stack class.
Stack stk = new Stack();
Or
Stack<type> stk = new Stack<>();
The Methods of Stack Class
//prints elements of the stack
Example: System.out.println("Elements in Stack: " + stk);
import java.util.Stack;
result = stk.empty(); //returns true if stack is empty
public class StackEmptyMethodExample
System.out.println("Is the stack empty? " + result);
{
}
public static void main(String[] args)
}
{
Output:
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
Is the stack empty? true
// checking stack is empty or not
Elements in Stack: [78, 113, 90, 120]
boolean result = stk.empty(); //returns true if stack is empty
Is the stack empty? false
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
Set Interface
• Set interface extends from Collection interface
• Set is an unordered collection
• It doesn’t allow duplicates
• If you add duplicates, it will replace the existing one
• It allows you to add only a single null value
• An iterator can be used to traverse through the list
Set Interface
• List interface has one legacy class called Vector, but Set doesn’t have
any legacy class

• Implementation classes for Set are


• TreeSet
• HashSet
• LinkedHashSet
SortedSet Interface
• SortedSet interface extends Set and declares the behavior of a set
sorted in ascending order
• SortedSet defines several methods that make set processing more
convenient
NavigableSet Interface
• NavigableSet interface extends SortedSet and declares the behavior
of a collection that supports the retrieval of elements based on the
closest match to a given value or values
HashSetClass
• HashSet extends AbstractSet and implements the Set interface

• It creates a collection that uses a hash table for storage


Example

OUTPUT
[Gamma, Eta, Alpha, Epsilon, Omega,
Beta]
LinkedHashSet Class
• LinkedHashSet class extends HashSet and adds no members of its
own

• LinkedHashSet maintains a linked list of the entries in the set, in the


order in which they were inserted
Example
TreeSet Class
• TreeSet extends AbstractSet and implements the NavigableSet
interface
• It creates a collection that uses a tree for storage
• Objects are stored in sorted, ascending order
• Access and retrieval times are quite fast
Example
Queue Interface
• The Queue interface extends Collection and declares the behavior of
a queue, which is often a first-in, first-out list
PriorityQueue Class
• PriorityQueue extends AbstractQueue and implements the Queue
interface

• It creates a queue that is prioritized based on the queue’s comparator

• Capacity grows automatically as elements are added


Deque Interface
• Deque interface extends Queue and declares the behavior of a double
ended queue
• Double-ended queues can function as standard, first-in, first-out
queues or as last-in, first out stacks
ArrayDequeClass
• ArrayDeque class extends AbstractCollection and implements the
Deque interface

• It adds no methods of its own

• ArrayDeque creates a dynamic array and has no capacity restrictions


Example
ACCESSING A COLLECTION VIA AN ITERATOR:

Iterator enables you to cycle through a collection, obtaining or removing elements.


ListIterator extends Iterator to allow bidirectional traversal of a list, and the modification of
elements.
The Methods Declared by Iterator:
Using an Iterator:

• Iterator is an object that enables you to traverse through a collection.

• Each of the collection classes provides an iterator() method that returns an iterator object to
the start of the collection.

• In general, to use an iterator to cycle through the contents of a collection, follow these steps:

 Obtain an iterator to the start of the collection by calling the collection’s iterator()method.

 Set up a loop that makes a call to hasNext().

 Have the loop iterate as long as hasNext() returns true.

 Within the loop, obtain each element by calling next().


ListIterator:
• Used for obtaining a iterator for collections that implement List.
• ListIterator gives us the ability to access the collection in either forward or backward direction.
• It has both next() and previous() method to access the next and previous element in the List.
The Methods Provided by ListIterator:
Advantage of Iterator over for-each method
 for-each construct can also be used for iterating through the Collection.
 Use Iterator instead of the for-each construct when you need to:
O Remove the current element
 The for-each construct hides the iterator, so you cannot call remove
O Iterate over multiple collectionsin parallel.
For (Object o:oa)
{
Fruit d2=(Fruit)o;
System.out.println(d2.name);
}
The For-Each Alternative to Iterators
// Use the for-each for loop to cycle through a collection.
import java.util.*;
class ForEachDemo
{
public static void main(String args[])
{
// Create an array list for integers.
ArrayList<Integer> vals = new ArrayList<Integer>();
// Add values to the array list.
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
// Use for loop to display the values.
System.out.print("Contents of vals:");
for(int v:vals)
System.out.print(v+"");
System.out.println();
// Now, sum the values by using a for loop.
int sum = 0;
for(int v:vals)
sum+ = v;
System.out.println("Sumofvalues:"+sum);
}}
Output:
Contents of vals:12345 Sum of values:15
Spliterators:
 A spliterator cycles through a sequence of elements.
 It offers substantially more functionality than does either
ListIterator.
 It provide support for parallel iteration of portions of the sequence.
The Methods Declared by Spliterator:
MAPS:

 A map is an object that stores associations between keys and values, or key/value pairs.
 Given a key, you can find its value. Both keys and values are objects.
 The keys must be unique, but the values may be duplicated.
 Some map scan accept a null key and null values, others cannot.

 Map don’t implement the Iterable interface. This means that you cannot cycle through a map
using a for-each style for loop. Furthermore, you can’t obtain an iterator to a map.
THE MAP INTERFACES:

The Map Interface:


The Map interface maps unique keys to values.
A key is an object that you use to retrieve a value at a later date.
Given a key and a value, you can store the value in a Map object.
After the value is stored, you can retrieve it by using its key.
The Methods Declared by Map:
The SortedMap Interface:
The SortedMap interface extends Map. It ensures that the entries are maintained in ascending order
based on the keys.
The Methods Declared by SortedMap:
The NavigableMap Interface:
The NavigableMap interface extends SortedMap and declares the behavior of a map that supports
the retrieval of entries based on the closest match toa givenkeyorkeys. The Methods Declared by
NavigableMap:
The Map.Entry Interface:
• The Map.Entry interface enables you to work with a map entry. Recall that the entrySet() method
declared by the Map interface returns a Set containing the map entries. Each of these set elements
is a Map.Entry object.
• The Non-Static Methods Declared by Map.Entry:
THE MAP CLASSES:

AbstractMap is a super class for all concrete map implementations.


The HashMap Class:
The HashMap class extends AbstractMap and implements the Map interface. It uses a hash table to
store the map. This allows the execution time of get() and put() to remain constant even for large
sets.
The following constructors are defined:
HashMap()

HashMap(Map<? extends K, ? extends V> m)


HashMap(int capacity)

HashMap(int capacity, float fillRatio)


Example:
import java.util.*;
class HashMapDemo {
public static void main (String args[]) {
// Create a hashmap.
HashMap<String, Double> hm = new HashMap<String, Double>();
// Put elements to the map
hm.put ("John Doe", new Double (3434.34)); hm.put ("Tom Smith", new Double (123.22)); hm.put
("JaneBaker",new Double (1378.00)); hm.put ("Tod Hall", new Double (99.22)); hm.put
("RalphSmith",new Double (-19.08));
// Get a set of the entries.
Set<Map.Entry<String, Double>> set = hm.entrySet();
//Display the set.
for (Map.Entry<String, Double> me: set)
{ System.out.print(me.getKey()+":");
System.out.println(me.getValue());
}
System.out.println();
// Deposit 1000 into John Doe’s account.
Double balance = hm.get ("John Doe");
hm.put ("John Doe",balance+1000);
System.out.println ("John Doe’s new balance: "+hm.get("John Doe"));
}
}
Output:
Tod Hall:99.22
John Doe:3434.34
Ralph Smith:-19.08
Tom Smith:123.22
Jane Baker:1378.0
John Doe’s new balance: 4434.34
The TreeMap Class:
The TreeMap class extends AbstractMap and implements the NavigableMap interface. It creates
maps stored in a tree structure. A TreeMap provides an efficient means of storing key/valuepairs in
sorted order and allows rapid retrieval.
The following TreeMap constructors are defined:
TreeMap()
TreeMap(Comparator<? superK> comp) TreeMap(Map< ? extends K, ? extends V> m)
TreeMap(SortedMap<K, ?extendsV> sm)
Example:
import java.util.*;
class TreeMapDemo {
public static void main (String args[]) {
//Create a treemap.
TreeMap <String, Double> tm = new TreeMap <String, Double>();
//Put elements to the map.
tm.put("John Doe", new Double(3434.34));
tm.put("Tom Smith", new Double(123.22));
tm.put("Jane Baker",new Double(1378.00));
tm.put("Tod Hall", new Double(99.22));
tm.put("Ralph Smith",new Double(-19.08));
//Get a set of the entries.
Set<Map.Entry<String, Double>> set = tm.entrySet();
//Display the elements.
for(Map.Entry<String,Double>me:set)
{ System.out.print(me.getKey()+":");
System.out.println(me.getValue());
}
System.out.println();
//Deposit 1000 into John Doe’s account.
double balance = tm.get("John Doe");
tm.put("John Doe",balance+1000);
System.out.println("John Doe’s new balance:"+tm.get("John Doe"));
}
}
Output:
Jane Baker:1378.0
John Doe:3434.34
Ralph Smith:-19.08
Tod Hall:99.22
Tom Smith: 123.22
John Doe's new balance: 4434.34
The LinkedHashMap Class:
 LinkedHashMap extends HashMap.
 It maintains a linked list of the entries in the map, in the order in which they were inserted.
 This allows insertion-order iteration over the map. That is, when iterating through a collection-view
of a LinkedHashMap, the elements will be returned in the order
in which they were inserted.
 You can also create a LinkedHashMap that returns its elements in the order in
which they were last accessed.
LinkedHashMap defines the following constructors:
LinkedHashMap( )
LinkedHashMap(Map<? extends K, ? extends V> m)

LinkedHashMap(int capacity)
LinkedHashMap(int capacity, float fillRatio)

LinkedHashMap(int capacity, float fillRatio, boolean

Order)
The IdentityHashMap Class:
IdentityHashMap extends AbstractMap and implements the Map interface. It is similar to
HashMap except that it uses reference equality when comparing elements.
The EnumMap Class:
EnumMap extends AbstractMap and implements Map. It is specifically for use with
keys of an enum type.
Topics
 Introduction 
 Matcher class
 Regex methods
 Basic regexes
 String match
 String replace
 Wildcards and anchors
 EXAMPLES
INTRODUCTION
The regular expression package, java.util.regex lets you perform sophisticated pattern matching operations.

Regular expressions (regex) are powerful tools for pattern matching and manipulating strings. In Java, regular
expressions are supported through the java.util.regex package. Regular expressions allow you to define patterns to match, search,
and replace specific text patterns within a larger string.

/[a-zA-Z_\-]+@(([a-zA-Z_\-])+\.)+[a-zA-Z]{2,4}/

• regular expression ("regex"): describes a pattern of text

• can test whether a string matches the expr's pattern

• can use a regex to search/replace characters in a string

• very powerful, but tough to read

• regular expressions occur in many places:

• text editors (TextPad) allow regexes in search/replace

• languages: JavaScript; Java Scanner, String split

• Unix/Linux/Mac shell commands (grep, sed, find, etc.)


MATCHER CLASS
• The Matcher class in Java is part of the java.util.regex package and is
used to perform matching operations on input text using regular
expressions. It works in conjunction with the Pattern class to apply a
regex pattern to a string and find matches or perform other
operations.
REGEX METHODS
.match(regexp) returns first match for this string
against the given regular
expression; if global /g flag is
used, returns array of all matches
.replace(regexp, text) replaces first occurrence of the
regular expression with the given
text; if global /g flag is used,
replaces all occurrences
.search(regexp) returns first index where the
given regular expression occurs
.split(delimiter[,limit]) breaks apart a string into an array
of strings using the given regular
as the delimiter; returns the
array of tokens
BASIC REGEX
/abc/

• a regular expression literal is written /pattern/


• the simplest regexes simply match a given substring

• the above regex matches any line containing "abc"


• YES : "abc", "abcdef", "defabc", ".=.abc.=."
• NO : "fedcba", "ab c", "AbC", "Bash", ...
WILDCARDS AND ANCHORS
. (a dot) matches any character except \n
• /.oo.y/ matches "Doocy", "goofy", "LooPy", ...
• use \. to literally match a dot . character

^ matches the beginning of a line; $ the end


• /^if$/ matches lines that consist entirely of if

\< demands that pattern is the beginning of a word;


\> demands that pattern is the end of a word
• /\<for\>/ matches lines that contain the word "for"
STRING MATCH
string.match(regex)

• if string fits pattern, returns matching text; else null


• can be used as a Boolean truthy/falsey test:
if (name.match(/[a-z]+/)) { ... }

• g after regex for array of global matches


• "obama".match(/.a/g) returns ["ba", "ma"]

• i after regex for case-insensitive match


• name.match(/Marty/i) matches "marty", "MaRtY"
STRING REPLACE
string.replace(regex, "text")

• replaces first occurrence of pattern with the given text


• var state = "Mississippi";
state.replace(/s/, "x") returns "Mixsissippi"

• g after regex to replace all occurrences


• state.replace(/s/g, "x") returns "Mixxixxippi"

• returns the modified string as its result; must be stored


• state = state.replace(/s/g, "x");
SPECIAL CHARACTERS
| means OR
• /abc|def|g/ matches lines with "abc", "def", or "g"
• precedence: ^Subject|Date: vs. ^(Subject|Date):
• There's no AND & symbol. Why not?

() are for grouping


• /(Homer|Marge) Simpson/ matches lines containing
"Homer Simpson" or "Marge Simpson"

\ starts an escape sequence


• many characters must be escaped: / \ $ . [ ] ( ) ^ * + ?
• "\.\\n" matches lines containing ".\n"
EXAMPLE 1
public class RegexExample {
public static void main(String[] args) {
String text = "Hello, my name is John. I live in 123 Main Street.";
String regex = "\\d+";
// Find matches
String[] matches = text.split(regex);
// Print matches
for (String match : matches) {
System.out.println("Match found: " + match);
}
}
}
OUTPUT
Match found: Hello, my name is John. I live in
Match found: Main Street.
EXAMPLE 2
public class RegexExample {
public static void main(String[] args) {
String text = "Hello, my name is John. I live in 123 Main Street.";
String regex = "\\d+";
String replacement = "[REDACTED]";
// Replace matches
String replacedText = text.replace(regex, replacement);
// Print replaced text
System.out.println("Replaced text: " + replacedText);
}
}
OUTPUT
Replaced text: Hello, my name is John. I live in [REDACTED] Main Street.

You might also like