Collection in Java A collection in Java is a framework that provides an architecture to store and manipulate a groupof objects. Java Collections can achieve all the operations that you perform on data such assearching, sorting, insertion, manipulation, and deletion. Key Points: Collections are used to store, retrieve, manipulate, and communicate aggregate data. Collections can hold both homogeneous and heterogeneous data. They can dynamically grow and shrink in size. Collection Framework in Java The Collection Framework provides a unified architecture for representing and manipulating collections. All thecollections frameworkscontain the following: Interfaces: Theseareabstract data types that represent collections.The interfaces allow collections to be manipulated independently of the detailsof their representation. 1.Collection 3.Set 5.Map 2.List 4.Queue Implementations: Thesearethe concrete implementations of the collection interfaces. Essentially, they arereusable data structures. 1ArrayList 3. Linkedlist 5.HashSet 2.TreeSet 4.HashMap 6.TreeMap Algorithms: Theseare the methods that perform useful computations, such assearching and sorting, on objects that Iteratorlnterface The Iterator interface provides a way to access elements of a collection sequentially without exposing the underlying structure. It is part of the java.util packageand is a universal iterator for all collections. Key Points: Methods: booleanhasNext(): Returns true if there aremore elementsto iterate over. E next(): Returns the next elementin the iteration. void remove(): Removes the last elementreturned by the iterator (optional operation). t Usage: The Iterator interface is used to traverse collections such as List, Set, and Map. It supports both read and remove operations. wArayListo): List<String> list = new list.add("A"); list.add("B"); list.add("C"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext() { String element = iterator. next(); System.out, printin (element);
computations, such as searching and sorting, on objects that implement collection interfaces. Advantages of Collection Framework Consistent API: The collection interfaces have a basic set of operations (such as addingand removing)that are extended by all implementations. ReducesProgramming Effort: By providing useful data structures and algorithms, the Collections Framework reduces the programming effort. Java Collections Framework The Java Collections Framework is structured asa unified architecture for representing and manipulating collections. The hierarchy is broadly divided into three major groups: List, Set,and Queue, which extend the Collection interface, Map, which is a separate hierarchy. Here are the importantpoints for each component: Collection Interface The root interface of the collections framework. Collection Interface The Collection interface is the root of the collection hierarchy. It represents a groupof objects known as elements. The Collection interface is part of the java.util package. Key Points: Methods: booleanadd(Ee): Ensures that this collection contains the specified element. booleanremove(Objecto): Removes a single instance of the specified elementfrom this collection. int size(): Returns the number of elementsin this collection. booleanisEmpty(): Returns true if this collection contains no elements. booleancontains(0bject o): Returns true if this collection contains the specified element. Iterator<E> iterator(): Returns an iterator over the
It provides common methods ikeadd(), remove(), size(), clear(), contains(), and iterator() Map Interface Represents a mapping between a key and a value. Does not extend the Collection interface. Provides methods to put, get,remove elementsbased on a key. Collection interface Map Interface ashMap Aryist nkedashMap nkedList eeMap ector t-Hashtabie Stack Hashset nkedkashset reeSet PoortyQieae +-DequeInterface +-ArrayDeque +-Linkedist Decue elementsin this collection. boolean addAl|(Collection<? extendsE> c): Adds all of the elementsin the specified collection to this collection. void clear(): Removes all of the elements from this collection. Subinterfaces: 1.List 2.Set 3.Queue Usage: The Collection interface provides the base functionality forall collections. Collection<String> collection = new ArrayList<>(); collection.add("A"); collection.add("B"): collection.add("C"); for (String elerent : collection) { System.out printin(element); List Interface The List interface extendsthe Collection interface and represents an Basic Operations l.boolean add( e) 6.void add(int index, element)
I|method 2 list.add("A"; list. add("B"; list.add("C"); for (int i = 0;i< list.size(); i++) ( System.out. printin list. get(i); System.0ut.printin(" After modihcation:+arrayList); I/Removing elements arrayList.remove("C"); System.out. printin ("After removal:"+ arrayList); / Checking size System.out.printin("Size of ArrayList:" + arrayList. size(): 1/ Checking if ArrayList contains an element System.out. printin(" Does Arraylist contain 'A'? "+ arraylist.contains("A"); Iteratorvs Listiterator Faature Iterator Listiterator /Clearing theArrayList arraylist.clear();: System.out.printin ("After clearing:" + arrayList); Applicable to Collection List Traversal Direction Forward onty Both forward and backoard Obtaining terator hastiext( ext() hesPrevseus() collectin.iterator()' Nc "it.itIterater() LinkedlList LinkedList is a doubly linked list implementation of the List interface. It is part of the Java Collections Framework and is found in the java.util package. Previo() tIndes() Unlike ArrayList, which uses a dynamic array, LinkedList uses a doubly ole
rviousndes()' Ne ( ) No set(E) No ArrayList ArrayList is a resizable array implementation of the List interface. It is part of the Java Collections Framework and is found in the java.util package. Arraylist allows for dynamic arrays that can grow asneeded, which means it can change its size during runtime. Key Points: Unlike arrays in Java, ArrayList can grow and shrink in size dynamically. Allows duplicate elements. Provides fast random access to elements. Initial capacity is 10, but it grows automatically aselementsare added. Key Points: Doubly Linked: Each element in a LinkedList is stored in a node that contains a reference to the next and previous elements. Dynamic Size: Can grow and shrink dynamically. Allows duplicate elements. Efficient for adding or removingelementsanywhere in the list. Slowerthan ArrayList for random access (get(), as it requires traversing from the head or tail. Basic Operations: (SameasArraylist ) import java.util.: public class LinkedListExample ( public static void main(Stringl] args) { 1/Create oLinkedList LinkedList<String> linkedlist = new LinkedList<>): HAdding elements linkedList.add("Apple"); linkedList.add("Banana"); linkedList. add("Cherry" ); import java. util.Vector; public classVectorExample { public staticvoid main (String|] args) {
orderedcollection (also known asa sequence). The user can access elementsby their integer index (position in the list) and search for elementsin the list. Key Points: Methods: 2.get(int index) 3. remove(int index) 4. int size() 5. booleancontains(e) set(int index, element) 8.boolean remove(e) 9. void clear() void add(int index, E element):Inserts the specified elementatthe specified position in this list. E get(int index): Returns the elementat the specified position in this list. Eset(int index, E element): Replaces the element at the specified position in this list with the specified element. E remove(intindex): Removes the element at the specified position in this list. int indexOf(object o): Returns the index of the first OCcurrence of the specified element in thislist. Listiterator<E> listlterator(): Returns a list iterator over the elementsin this list. Implementations: 1.ArrayList 2. LinkedList 3. Vector 4.Stack Usage: The List interface allows for ordered collections that can contain duplicate elements. List<String> list = new ArrayList<): I/ List<integer> numbers = Arrays.asList(5. 2. 8.13):method 1 import java. util." public class ArrayListExample { public static void main(String] args) { 7/Creating on Araylist List<String> arrayList = new ArrayList<>(); 1/Adding elements arrayList.add("A"): arraylist. add("B"): arrayList.add("C"); arrayList. add("D"); HAccessing elements System.out. printin("Element at index 2:" + arrayList. get(2)); iteroting eiements for (String element : arrayList) { System.out.printin(element); /Modifying elements arrayList.set(1, "E");
linkedList.set(1,"Orange"); 1/Modifyelement linkedList.add(2, "Grape"); //Add anelement linkedList.remove("Apple"); // Remove element WCheckif "Banana"is present booleancontainsBanana =linkedList.contains(" Banana"); System.out. printin(" Does LinkedList contain'Banana'?"+ containsBanana); System.out, printin ("Print forward order element"): Listiterator<String> iterator = linkedList. listiterator(): while (iterator.hasNext() ( System.out, printin( iterator.next()); Vector<String> vector = new Vector<>); vector.add("A"); IAdding elements vector.add("B"); vector.add("C"); IAccessing elements System.out printin ("Element at index 1: " + vector.get(1); 1/ Removing element vector.remove(2); /Size of vector System.out. printin("Size of vector: " + vector.size): System.out, printin ("Print reverse order element"); while (iterator.hasPrevious() System.out. printin( iterator.previous(): Arraylist(Collection<? extends E>c) Creates a list containing the elementsof the specified collection, in the order they arereturned by the collection's iterator. It is same For Linked List istcString oviciogi ict asl istA C Stack Stack is a subelass of Vector that implementsa last-in, first-out (LIFO) stack of objects. Methods: push(E item): Pushes an item onto the top of the stack. pop(): Removes the object at the top of the stack and returns it. peek(): Looks at the object at the top of the stack without removing it. isEmpty(): Checksif the stack is empty.
List<String existinglist = Arrays.asList("A","B","C"); Arraylist<String> list = new ArrayList<>(existingList); System.out, printin(list): //Output: (A, B, C] LinkedList(Collection<? extendsE> ) List<String> arraylist = new ArrayListo(); arrayList.add("Apple"); arrayList.add("Banana"); arrayList.add("Cherry"); 1/ Createo Linkedist using the ArrayList elerments LinkedList<String> linkedlist= new LinkedList<>(arrayList);: import java.util.Stack; public class StackExample public static void main (String] args) { Stack<String> stack = new Stacko); 1IPushing elements stack push("A"); stack push-B"); stack.push("C"); IPeeking the top element System.out. printin ("Topelement:"+ stack.peek());
LinkedList vs ArrayList LinkedList provides methods like addFirst, addLast, getFirst, getLast, removeFirst, removelast, offerFirst,offerlast, peekFirst, peeklast, pollfirst, pollLast, descendingiterator for efficient insertion, removal, and traversal operations from both ends. ArrayList is optimized for random access and efficient element insertion/removal in the middle. Choosing between them depends on the use case: Use LinkedList for frequent insertions/removals at both ends or sequential traversal. Use ArrayList for scenarios requiring random access or faster access by index. Vector Vector is a part of the Java Collections Framework and implementsa growablearray of objects. It is synchronized, making it thread-safe, but can have performance overheaddue to synchronization. Methods: add(e): Adds an elementto the end of the vector. get(int index): Returns the elementat the specified position. remove(int index): Removes the elementat the specified position. size(): Returns the number of elementsin the vector. System.out, printin(" Poppedelement:" + stack.pop): / Checking if stock is empty System.out. printin("Is stack empty?"+stack.isEmpty0): Queue Interface Queue is a collection designed for holding elementsprior to processing. it typicallyorders elementsin a FIFO (first-in, first-out) manner. Implementations include LinkedList and PriorityQueue. Methods: add(e): Inserts the specified element into the queue (throwsan exception if it fails). offer(e): Inserts the specified elementinto the queue (returns false if it fails). remove():Retrieves and removes the head of the queue (throws NoSuchElementException an exception if the queue is empty). poll(): Rtrieves and removes the head of the queue (returns nul if the queue is empty). peek(): Retrieves, but does not remove,the head of the queue (returns null if the queue is empty).
importjava.util.LinkedList; importjava.util.Queue; public class QueueExample( public staticvoid main (String|]args) { Queue<String>queue = new LinkedList<>(): IAdding elements queue.add("A"); queue.add("B"); queue.add("C"); 1/ Peeking the heod element System.out. printin ("Headelement: " + queue.peek()): 1/ inkedHashSet xample Set<String> linkedHashSet = new LinkedHashSet<>(); linkedHashSet.add("B"); linkedHashSet.add ("A"); linkedHashSet. add("C"); System.out. printin (" LinkedHash Set:"+ linkedHashSet): / 1TreeSet exomple Set<String treeSet = new TreeSeto); treeSet.add("B"): treeSet.add("A"); treeSet.add('C"): System.out, prhtin ("TreeSet:"+treeSet); /ABC BAC 1IPolling elements System.out. printin("Polledelement:"+ queue.poll()): 1/Checking the size System.out.printin("Size of queue:"+ queue.size(); HashSet: Fostest for basic operotions, no guaranteedorder. LinkedHashSet: Maintoins insertion order, slower thon HashSet. TreeSet: Maintains elements in sorted order, slower than HashSet ond LinkedHoshSet. Map Interface
Set Interface Represents a collection that cannot contain duplicate elements. It models the mathematical set abstraction. Does not guaranteethe order of elements. Allows at most one null element. Implementations include HashSet, LinkedHashSet, and TreeSet. HashSet Implementsthe Set interface using a hash table. It does not guarantee the order of elements. Offers constant-time performancefor basic operations (add, remove, contains). Does not maintain the insertion order. Allows null elements. Represents a collection of key value pairs where each key is unique. Maps keys to values and does not allow duplicate keys. methods for adding, accessing, removing, and checking for key-value pairs. HashMap Class Implementsthe Map interface using a hash table. Does not guaranteethe order of key-value pairs. Provides constant-time performancefor basic operations (put, get, remove)on average. Allows null values and one null key. import java.util.HashMap, importjava.util.Map;
LinkedHash Set Extends HashSetand maintains a doubly-linked list of entries to preserve the insertion order. Iterates over elementsin insertion order. Slowerthan HashSet for basic operations due to maintaining order. Allows null elements. SortedSet Interface public class HashMapExample public static void main(Stringl] args) ( Map<String,Integer> hashMap = new HashMap<>(); hashMap.put("One",1); hashMap.gt("Two", 2); hashMap.put("Three", 3); System.out, printin ("HashMap:" + hashMap); Extends Set and maintains elements in sorted order defined by their natural ordering or a comparator. Provides methods for accessing elementsby their position in the sorted set. LinkedHashMap Class Evtende HachMan and maintainc incortion order of kove
Set. Implementations include TreeSet. TreeSet ImplementsSortedSet using a tree structure (red-black tree). Maintains elementsin sorted order (ascending by default or basedon a custom comparator). Slowerperformancefor basic operations compared to HashSetand LinkedHashSet. Does not allow null elements. Example Of All Sets interface import java.util."; public class SetExamples{ public static void main(Stringl] args) { 1/HashSetexomple Set<String> hashSet =new HashSet<>(); hashSet.add("B"); hashSet.add("A"); hashSet.add("C"); System.out.printin (" Hash Set:" +hashSet); /CB A Extends HashMap and maintains insertion order of keys. Iterates over elementsin the order they were inserted. Slowerperformancefor basic operations compared to HashMap due to maintaining order. Allows null values and one null key. import java.util. LinkedHashMap; importjava.util.Map; public class LinkedHashMapExample { public staticvoid main(Stringl] args) { Map<String, Integer> linkedHashMap = new LinkedHashMap<>(): linkedHashMap.put (One", 1); linkedHashMap.put(" Two",2);: linkedHashMap.put("Three", 3): System.out. printin("LinkedHashMap:" +linkedHashMap);
HoshMop:Fastest for basic operotions, no order guarantee. LinkedHashMap: Maintoins insertion order, inherits from HoshMap. TreeMap: Maintains keys in sorted order, slower for basic operotions due to sorting.* Hashtable Class The Hashtable class in Java provides a basic implementation of a hash table, which maps keys to values. It inherits from the Dictionary class and implementsthe Map interface, making it similar to HashMap but with some differences: Hashtable is synchronized, Neither keys nor values can be nul import java.util.Hashtable; int[] nums = (5, 2,8, 1, 3}; Arrays.sort(nums); //Sorts nums array in ascending order Sorting Collections 1.Collections.sort():Sorts collections such aslists using natural ordering (if elementsimplement Comparable)or a specified Comparator. List<String> names =new ArrayList<>); names.add("Alice" );: names.add("Bob"); Collectils.sort(names); //Sorts olphobetically (notural order) 2.Sorting with Comparator: ascending order use: Comparator.naturalOrder() and descending order use: Comparator.reverseOrder() public class HashtableExample( public staticvoid main(Stringl] args) { /Using Hoshtable HachtabloStrinalntoGArhachtablo noM Hachtahlocs List<String> names = new ArrayList<>(); names.add("Alice"): names.add("Bob"); Collections.sort(names, Comparator.reverse Order(): //Sorts in
System.out. printin("Hashtable:" + hashtable); Iterators used in Map and Set import java. util."; Comparable Interface Comparable is an interface in the java.lang package. It declares one method compareTo()which compares the current object (this) with anotherobject of the same type. Classes that implement Comparable can be sorted automatically using methods like Arrays.sort() or Collections.sort(). public class SetMaplterationExample { public static void main(Stringl] args) ( 7Create a HashSet Set<String> set = new HashSetc>); HAdd elements to the Set set.add("Apple"); set.add("Banana"); set.add("Orange"); 1/terating over the Setusing for-eoch loop System.out. printin("Elements in the Set:"); for (String element : set) ( System.out. printin(element); public interface Comparable<T>{ public int compareTo(T o); Example of Comparable InterFace public class Student implementsComparable<Student>{ private String name; private int age; 1H Constructor public Student(String name, int age) { this.name = rtome; this.ageage; 1/Create oHashMop Map<String, Integer> map = new HashMap<o);
public int compareTo(Student other) ( /Compore students based on age return Integer.compare(this.age, other.age): 7Exomple usoge in moin method public staticvoid main(String [] args) { List<Student> students =new ArrayList<> (): students.add(new Student("Alice", 20)); students.add(newStudent ("Bob", 18); students.add(new Student("Charlie", 22)); /Sorting using Collections.sort) (usesComparable) Collections.sort(students); /Printing sorted students System.out.printin ("Sorted Studentsby Age:"); for (Student student: students) ( System.out. printin (student); Properties Class Properties stores key-value pairs where both keys and values are strings. It supportsloading from and saving to files using load() and store() methods. Default values can be set and queried if a property is not found in the current instance. Java system properties (System-getProperties()) are accessible through a Properties object. Exampleusage involves setting, saving to file, loading, and accessing properties. lIt provides persistence for application settings like database connectionsand Ul configurations. methods : setProperty(String key, String value): Sets a key-value pair in the Properties object. getProperty(String key): Retrieves the value associated with a specified key. store(OutputStream out, String comments): Saves properties to an output stream, with optional comments.
Comparator Interface The Comparator interface in Java is located in the java.util package. It defines two methods:compare(T o1,T o2)and equals(Object obi). You typically create an instance of Comparatoreither asan anonymous class. Comparator is commonly used with sorting methods like Collections.sort() for lists or Arrays.sort() for arrays to define the order in which elementsshould be sorted. Example of Comparator Interface import java.util.; public class Student { private String name; private int age, public Student (String name, int age) ( this.name = name; this. age = age, int getAge() (return this. age;) load(InputStream in): Loads properties from an input stream. stringPropertyNames(): Returns keys where both the key and value are strings. import java.io."; import java.util.; public class Student( public staticvoid main(String[] args) ( Properties prop = new Properties(); /Setting properties prop.setProperty( "database.url", "jdbc:mysql:/ localhost:3306/mydb"); prop.setProperty( "database. user", "root"); p. setProperty "database. password","password");: prop. /Soving properties to afile try (OutputStreamoutput = new FileOutputStream("config. properties") ( prop.store(output, "DatabaseConfiguration"); System.out.printin ("Properties saved successfully."); } catch (1OException e) ( e.printStackTrace(): nuhlic staticunid mainLStrinalLarc)
public static void main(Stringl] args) { List<Student>students new ArrayListo: students.add(new Student("Alice,20): students.add (new Student("Bob", 18)): students.add(new Student(" Charlie", 22): HUsing Comporotor to sort by oge in descending order Comparator<Student> ageComparator a new Comparator<Student>() Override public int compare(Student s1, Student s2) ( return integer.compare(s2 getAge), s1 getAge()l: //Descending order /Looding properties from ofile try (InputStream input = new FileinputStream("config properties") { prop.load(input); System.out, printin("Propertiesloaded successfully."); /Display properties prop.forEach(key, value) -> ( System.out. printin (key +";"+value); 7 Sorong sTudents hst using ogeCormporotor Collections. sort(students, ageComparator); 1/ Accessing individuol property String dblUrl = prop.getProperty(" database. url"); System.out. printin ("Database URL:"+ dbUri);

java unit 4 pdf - about java collections

  • 1.
    Collection in Java A collectionin Java is a framework that provides an architecture to store and manipulate a groupof objects. Java Collections can achieve all the operations that you perform on data such assearching, sorting, insertion, manipulation, and deletion. Key Points: Collections are used to store, retrieve, manipulate, and communicate aggregate data. Collections can hold both homogeneous and heterogeneous data. They can dynamically grow and shrink in size. Collection Framework in Java The Collection Framework provides a unified architecture for representing and manipulating collections. All thecollections frameworkscontain the following: Interfaces: Theseareabstract data types that represent collections.The interfaces allow collections to be manipulated independently of the detailsof their representation. 1.Collection 3.Set 5.Map 2.List 4.Queue Implementations: Thesearethe concrete implementations of the collection interfaces. Essentially, they arereusable data structures. 1ArrayList 3. Linkedlist 5.HashSet 2.TreeSet 4.HashMap 6.TreeMap Algorithms: Theseare the methods that perform useful computations, such assearching and sorting, on objects that Iteratorlnterface The Iterator interface provides a way to access elements of a collection sequentially without exposing the underlying structure. It is part of the java.util packageand is a universal iterator for all collections. Key Points: Methods: booleanhasNext(): Returns true if there aremore elementsto iterate over. E next(): Returns the next elementin the iteration. void remove(): Removes the last elementreturned by the iterator (optional operation). t Usage: The Iterator interface is used to traverse collections such as List, Set, and Map. It supports both read and remove operations. wArayListo): List<String> list = new list.add("A"); list.add("B"); list.add("C"); Iterator<String> iterator = list.iterator(); while (iterator.hasNext() { String element = iterator. next(); System.out, printin (element);
  • 2.
    computations, such assearching and sorting, on objects that implement collection interfaces. Advantages of Collection Framework Consistent API: The collection interfaces have a basic set of operations (such as addingand removing)that are extended by all implementations. ReducesProgramming Effort: By providing useful data structures and algorithms, the Collections Framework reduces the programming effort. Java Collections Framework The Java Collections Framework is structured asa unified architecture for representing and manipulating collections. The hierarchy is broadly divided into three major groups: List, Set,and Queue, which extend the Collection interface, Map, which is a separate hierarchy. Here are the importantpoints for each component: Collection Interface The root interface of the collections framework. Collection Interface The Collection interface is the root of the collection hierarchy. It represents a groupof objects known as elements. The Collection interface is part of the java.util package. Key Points: Methods: booleanadd(Ee): Ensures that this collection contains the specified element. booleanremove(Objecto): Removes a single instance of the specified elementfrom this collection. int size(): Returns the number of elementsin this collection. booleanisEmpty(): Returns true if this collection contains no elements. booleancontains(0bject o): Returns true if this collection contains the specified element. Iterator<E> iterator(): Returns an iterator over the
  • 3.
    It provides commonmethods ikeadd(), remove(), size(), clear(), contains(), and iterator() Map Interface Represents a mapping between a key and a value. Does not extend the Collection interface. Provides methods to put, get,remove elementsbased on a key. Collection interface Map Interface ashMap Aryist nkedashMap nkedList eeMap ector t-Hashtabie Stack Hashset nkedkashset reeSet PoortyQieae +-DequeInterface +-ArrayDeque +-Linkedist Decue elementsin this collection. boolean addAl|(Collection<? extendsE> c): Adds all of the elementsin the specified collection to this collection. void clear(): Removes all of the elements from this collection. Subinterfaces: 1.List 2.Set 3.Queue Usage: The Collection interface provides the base functionality forall collections. Collection<String> collection = new ArrayList<>(); collection.add("A"); collection.add("B"): collection.add("C"); for (String elerent : collection) { System.out printin(element); List Interface The List interface extendsthe Collection interface and represents an Basic Operations l.boolean add( e) 6.void add(int index, element)
  • 4.
    I|method 2 list.add("A"; list. add("B"; list.add("C"); for(int i = 0;i< list.size(); i++) ( System.out. printin list. get(i); System.0ut.printin(" After modihcation:+arrayList); I/Removing elements arrayList.remove("C"); System.out. printin ("After removal:"+ arrayList); / Checking size System.out.printin("Size of ArrayList:" + arrayList. size(): 1/ Checking if ArrayList contains an element System.out. printin(" Does Arraylist contain 'A'? "+ arraylist.contains("A"); Iteratorvs Listiterator Faature Iterator Listiterator /Clearing theArrayList arraylist.clear();: System.out.printin ("After clearing:" + arrayList); Applicable to Collection List Traversal Direction Forward onty Both forward and backoard Obtaining terator hastiext( ext() hesPrevseus() collectin.iterator()' Nc "it.itIterater() LinkedlList LinkedList is a doubly linked list implementation of the List interface. It is part of the Java Collections Framework and is found in the java.util package. Previo() tIndes() Unlike ArrayList, which uses a dynamic array, LinkedList uses a doubly ole
  • 5.
    rviousndes()' Ne ( ) No set(E)No ArrayList ArrayList is a resizable array implementation of the List interface. It is part of the Java Collections Framework and is found in the java.util package. Arraylist allows for dynamic arrays that can grow asneeded, which means it can change its size during runtime. Key Points: Unlike arrays in Java, ArrayList can grow and shrink in size dynamically. Allows duplicate elements. Provides fast random access to elements. Initial capacity is 10, but it grows automatically aselementsare added. Key Points: Doubly Linked: Each element in a LinkedList is stored in a node that contains a reference to the next and previous elements. Dynamic Size: Can grow and shrink dynamically. Allows duplicate elements. Efficient for adding or removingelementsanywhere in the list. Slowerthan ArrayList for random access (get(), as it requires traversing from the head or tail. Basic Operations: (SameasArraylist ) import java.util.: public class LinkedListExample ( public static void main(Stringl] args) { 1/Create oLinkedList LinkedList<String> linkedlist = new LinkedList<>): HAdding elements linkedList.add("Apple"); linkedList.add("Banana"); linkedList. add("Cherry" ); import java. util.Vector; public classVectorExample { public staticvoid main (String|] args) {
  • 6.
    orderedcollection (also knownasa sequence). The user can access elementsby their integer index (position in the list) and search for elementsin the list. Key Points: Methods: 2.get(int index) 3. remove(int index) 4. int size() 5. booleancontains(e) set(int index, element) 8.boolean remove(e) 9. void clear() void add(int index, E element):Inserts the specified elementatthe specified position in this list. E get(int index): Returns the elementat the specified position in this list. Eset(int index, E element): Replaces the element at the specified position in this list with the specified element. E remove(intindex): Removes the element at the specified position in this list. int indexOf(object o): Returns the index of the first OCcurrence of the specified element in thislist. Listiterator<E> listlterator(): Returns a list iterator over the elementsin this list. Implementations: 1.ArrayList 2. LinkedList 3. Vector 4.Stack Usage: The List interface allows for ordered collections that can contain duplicate elements. List<String> list = new ArrayList<): I/ List<integer> numbers = Arrays.asList(5. 2. 8.13):method 1 import java. util." public class ArrayListExample { public static void main(String] args) { 7/Creating on Araylist List<String> arrayList = new ArrayList<>(); 1/Adding elements arrayList.add("A"): arraylist. add("B"): arrayList.add("C"); arrayList. add("D"); HAccessing elements System.out. printin("Element at index 2:" + arrayList. get(2)); iteroting eiements for (String element : arrayList) { System.out.printin(element); /Modifying elements arrayList.set(1, "E");
  • 7.
    linkedList.set(1,"Orange"); 1/Modifyelement linkedList.add(2, "Grape");//Add anelement linkedList.remove("Apple"); // Remove element WCheckif "Banana"is present booleancontainsBanana =linkedList.contains(" Banana"); System.out. printin(" Does LinkedList contain'Banana'?"+ containsBanana); System.out, printin ("Print forward order element"): Listiterator<String> iterator = linkedList. listiterator(): while (iterator.hasNext() ( System.out, printin( iterator.next()); Vector<String> vector = new Vector<>); vector.add("A"); IAdding elements vector.add("B"); vector.add("C"); IAccessing elements System.out printin ("Element at index 1: " + vector.get(1); 1/ Removing element vector.remove(2); /Size of vector System.out. printin("Size of vector: " + vector.size): System.out, printin ("Print reverse order element"); while (iterator.hasPrevious() System.out. printin( iterator.previous(): Arraylist(Collection<? extends E>c) Creates a list containing the elementsof the specified collection, in the order they arereturned by the collection's iterator. It is same For Linked List istcString oviciogi ict asl istA C Stack Stack is a subelass of Vector that implementsa last-in, first-out (LIFO) stack of objects. Methods: push(E item): Pushes an item onto the top of the stack. pop(): Removes the object at the top of the stack and returns it. peek(): Looks at the object at the top of the stack without removing it. isEmpty(): Checksif the stack is empty.
  • 8.
    List<String existinglist =Arrays.asList("A","B","C"); Arraylist<String> list = new ArrayList<>(existingList); System.out, printin(list): //Output: (A, B, C] LinkedList(Collection<? extendsE> ) List<String> arraylist = new ArrayListo(); arrayList.add("Apple"); arrayList.add("Banana"); arrayList.add("Cherry"); 1/ Createo Linkedist using the ArrayList elerments LinkedList<String> linkedlist= new LinkedList<>(arrayList);: import java.util.Stack; public class StackExample public static void main (String] args) { Stack<String> stack = new Stacko); 1IPushing elements stack push("A"); stack push-B"); stack.push("C"); IPeeking the top element System.out. printin ("Topelement:"+ stack.peek());
  • 9.
    LinkedList vs ArrayList LinkedListprovides methods like addFirst, addLast, getFirst, getLast, removeFirst, removelast, offerFirst,offerlast, peekFirst, peeklast, pollfirst, pollLast, descendingiterator for efficient insertion, removal, and traversal operations from both ends. ArrayList is optimized for random access and efficient element insertion/removal in the middle. Choosing between them depends on the use case: Use LinkedList for frequent insertions/removals at both ends or sequential traversal. Use ArrayList for scenarios requiring random access or faster access by index. Vector Vector is a part of the Java Collections Framework and implementsa growablearray of objects. It is synchronized, making it thread-safe, but can have performance overheaddue to synchronization. Methods: add(e): Adds an elementto the end of the vector. get(int index): Returns the elementat the specified position. remove(int index): Removes the elementat the specified position. size(): Returns the number of elementsin the vector. System.out, printin(" Poppedelement:" + stack.pop): / Checking if stock is empty System.out. printin("Is stack empty?"+stack.isEmpty0): Queue Interface Queue is a collection designed for holding elementsprior to processing. it typicallyorders elementsin a FIFO (first-in, first-out) manner. Implementations include LinkedList and PriorityQueue. Methods: add(e): Inserts the specified element into the queue (throwsan exception if it fails). offer(e): Inserts the specified elementinto the queue (returns false if it fails). remove():Retrieves and removes the head of the queue (throws NoSuchElementException an exception if the queue is empty). poll(): Rtrieves and removes the head of the queue (returns nul if the queue is empty). peek(): Retrieves, but does not remove,the head of the queue (returns null if the queue is empty).
  • 10.
    importjava.util.LinkedList; importjava.util.Queue; public class QueueExample( publicstaticvoid main (String|]args) { Queue<String>queue = new LinkedList<>(): IAdding elements queue.add("A"); queue.add("B"); queue.add("C"); 1/ Peeking the heod element System.out. printin ("Headelement: " + queue.peek()): 1/ inkedHashSet xample Set<String> linkedHashSet = new LinkedHashSet<>(); linkedHashSet.add("B"); linkedHashSet.add ("A"); linkedHashSet. add("C"); System.out. printin (" LinkedHash Set:"+ linkedHashSet): / 1TreeSet exomple Set<String treeSet = new TreeSeto); treeSet.add("B"): treeSet.add("A"); treeSet.add('C"): System.out, prhtin ("TreeSet:"+treeSet); /ABC BAC 1IPolling elements System.out. printin("Polledelement:"+ queue.poll()): 1/Checking the size System.out.printin("Size of queue:"+ queue.size(); HashSet: Fostest for basic operotions, no guaranteedorder. LinkedHashSet: Maintoins insertion order, slower thon HashSet. TreeSet: Maintains elements in sorted order, slower than HashSet ond LinkedHoshSet. Map Interface
  • 11.
    Set Interface Represents acollection that cannot contain duplicate elements. It models the mathematical set abstraction. Does not guaranteethe order of elements. Allows at most one null element. Implementations include HashSet, LinkedHashSet, and TreeSet. HashSet Implementsthe Set interface using a hash table. It does not guarantee the order of elements. Offers constant-time performancefor basic operations (add, remove, contains). Does not maintain the insertion order. Allows null elements. Represents a collection of key value pairs where each key is unique. Maps keys to values and does not allow duplicate keys. methods for adding, accessing, removing, and checking for key-value pairs. HashMap Class Implementsthe Map interface using a hash table. Does not guaranteethe order of key-value pairs. Provides constant-time performancefor basic operations (put, get, remove)on average. Allows null values and one null key. import java.util.HashMap, importjava.util.Map;
  • 12.
    LinkedHash Set Extends HashSetandmaintains a doubly-linked list of entries to preserve the insertion order. Iterates over elementsin insertion order. Slowerthan HashSet for basic operations due to maintaining order. Allows null elements. SortedSet Interface public class HashMapExample public static void main(Stringl] args) ( Map<String,Integer> hashMap = new HashMap<>(); hashMap.put("One",1); hashMap.gt("Two", 2); hashMap.put("Three", 3); System.out, printin ("HashMap:" + hashMap); Extends Set and maintains elements in sorted order defined by their natural ordering or a comparator. Provides methods for accessing elementsby their position in the sorted set. LinkedHashMap Class Evtende HachMan and maintainc incortion order of kove
  • 13.
    Set. Implementations include TreeSet. TreeSet ImplementsSortedSet usinga tree structure (red-black tree). Maintains elementsin sorted order (ascending by default or basedon a custom comparator). Slowerperformancefor basic operations compared to HashSetand LinkedHashSet. Does not allow null elements. Example Of All Sets interface import java.util."; public class SetExamples{ public static void main(Stringl] args) { 1/HashSetexomple Set<String> hashSet =new HashSet<>(); hashSet.add("B"); hashSet.add("A"); hashSet.add("C"); System.out.printin (" Hash Set:" +hashSet); /CB A Extends HashMap and maintains insertion order of keys. Iterates over elementsin the order they were inserted. Slowerperformancefor basic operations compared to HashMap due to maintaining order. Allows null values and one null key. import java.util. LinkedHashMap; importjava.util.Map; public class LinkedHashMapExample { public staticvoid main(Stringl] args) { Map<String, Integer> linkedHashMap = new LinkedHashMap<>(): linkedHashMap.put (One", 1); linkedHashMap.put(" Two",2);: linkedHashMap.put("Three", 3): System.out. printin("LinkedHashMap:" +linkedHashMap);
  • 14.
    HoshMop:Fastest for basicoperotions, no order guarantee. LinkedHashMap: Maintoins insertion order, inherits from HoshMap. TreeMap: Maintains keys in sorted order, slower for basic operotions due to sorting.* Hashtable Class The Hashtable class in Java provides a basic implementation of a hash table, which maps keys to values. It inherits from the Dictionary class and implementsthe Map interface, making it similar to HashMap but with some differences: Hashtable is synchronized, Neither keys nor values can be nul import java.util.Hashtable; int[] nums = (5, 2,8, 1, 3}; Arrays.sort(nums); //Sorts nums array in ascending order Sorting Collections 1.Collections.sort():Sorts collections such aslists using natural ordering (if elementsimplement Comparable)or a specified Comparator. List<String> names =new ArrayList<>); names.add("Alice" );: names.add("Bob"); Collectils.sort(names); //Sorts olphobetically (notural order) 2.Sorting with Comparator: ascending order use: Comparator.naturalOrder() and descending order use: Comparator.reverseOrder() public class HashtableExample( public staticvoid main(Stringl] args) { /Using Hoshtable HachtabloStrinalntoGArhachtablo noM Hachtahlocs List<String> names = new ArrayList<>(); names.add("Alice"): names.add("Bob"); Collections.sort(names, Comparator.reverse Order(): //Sorts in
  • 15.
    System.out. printin("Hashtable:" +hashtable); Iterators used in Map and Set import java. util."; Comparable Interface Comparable is an interface in the java.lang package. It declares one method compareTo()which compares the current object (this) with anotherobject of the same type. Classes that implement Comparable can be sorted automatically using methods like Arrays.sort() or Collections.sort(). public class SetMaplterationExample { public static void main(Stringl] args) ( 7Create a HashSet Set<String> set = new HashSetc>); HAdd elements to the Set set.add("Apple"); set.add("Banana"); set.add("Orange"); 1/terating over the Setusing for-eoch loop System.out. printin("Elements in the Set:"); for (String element : set) ( System.out. printin(element); public interface Comparable<T>{ public int compareTo(T o); Example of Comparable InterFace public class Student implementsComparable<Student>{ private String name; private int age; 1H Constructor public Student(String name, int age) { this.name = rtome; this.ageage; 1/Create oHashMop Map<String, Integer> map = new HashMap<o);
  • 16.
    public int compareTo(Student other)( /Compore students based on age return Integer.compare(this.age, other.age): 7Exomple usoge in moin method public staticvoid main(String [] args) { List<Student> students =new ArrayList<> (): students.add(new Student("Alice", 20)); students.add(newStudent ("Bob", 18); students.add(new Student("Charlie", 22)); /Sorting using Collections.sort) (usesComparable) Collections.sort(students); /Printing sorted students System.out.printin ("Sorted Studentsby Age:"); for (Student student: students) ( System.out. printin (student); Properties Class Properties stores key-value pairs where both keys and values are strings. It supportsloading from and saving to files using load() and store() methods. Default values can be set and queried if a property is not found in the current instance. Java system properties (System-getProperties()) are accessible through a Properties object. Exampleusage involves setting, saving to file, loading, and accessing properties. lIt provides persistence for application settings like database connectionsand Ul configurations. methods : setProperty(String key, String value): Sets a key-value pair in the Properties object. getProperty(String key): Retrieves the value associated with a specified key. store(OutputStream out, String comments): Saves properties to an output stream, with optional comments.
  • 17.
    Comparator Interface The Comparatorinterface in Java is located in the java.util package. It defines two methods:compare(T o1,T o2)and equals(Object obi). You typically create an instance of Comparatoreither asan anonymous class. Comparator is commonly used with sorting methods like Collections.sort() for lists or Arrays.sort() for arrays to define the order in which elementsshould be sorted. Example of Comparator Interface import java.util.; public class Student { private String name; private int age, public Student (String name, int age) ( this.name = name; this. age = age, int getAge() (return this. age;) load(InputStream in): Loads properties from an input stream. stringPropertyNames(): Returns keys where both the key and value are strings. import java.io."; import java.util.; public class Student( public staticvoid main(String[] args) ( Properties prop = new Properties(); /Setting properties prop.setProperty( "database.url", "jdbc:mysql:/ localhost:3306/mydb"); prop.setProperty( "database. user", "root"); p. setProperty "database. password","password");: prop. /Soving properties to afile try (OutputStreamoutput = new FileOutputStream("config. properties") ( prop.store(output, "DatabaseConfiguration"); System.out.printin ("Properties saved successfully."); } catch (1OException e) ( e.printStackTrace(): nuhlic staticunid mainLStrinalLarc)
  • 18.
    public static voidmain(Stringl] args) { List<Student>students new ArrayListo: students.add(new Student("Alice,20): students.add (new Student("Bob", 18)): students.add(new Student(" Charlie", 22): HUsing Comporotor to sort by oge in descending order Comparator<Student> ageComparator a new Comparator<Student>() Override public int compare(Student s1, Student s2) ( return integer.compare(s2 getAge), s1 getAge()l: //Descending order /Looding properties from ofile try (InputStream input = new FileinputStream("config properties") { prop.load(input); System.out, printin("Propertiesloaded successfully."); /Display properties prop.forEach(key, value) -> ( System.out. printin (key +";"+value); 7 Sorong sTudents hst using ogeCormporotor Collections. sort(students, ageComparator); 1/ Accessing individuol property String dblUrl = prop.getProperty(" database. url"); System.out. printin ("Database URL:"+ dbUri);