Automation QA Testing Course Content

Collections

                            COLLECTIONS

The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

Hierarchy of Collection Framework

Let us see the hierarchy of collection framework.The java.util package contains all the classes & Interfaces



Methods of Collection:

 1)public boolean add(Object element)  is used to insert an element in this collection.

 collectionname.add(Object element);

 2)public boolean addAll(collection c)    is used to insert the specified collection elements in the invoking collection.
 collectionname.addAll(collection c);

 3)public boolean remove(Object element):is used to delete an element from this collection.
 collectionname.remove(Object element);

 4)public boolean removeAll(Collection c)       is used to delete all the elements of specified collection from the invoking collection.
 Collectionname.removeAll(Collection c);
 5)public int size():return the total number of elements in the collection.
 int count=collectionname.size();

 6)public void clear()    removes the total no of element from the collection.
 collectionname.clear();
 7)public boolean contains(object element)    is used to search an element.
 boolean b=collectionname.contains(object element);
 8)public Iterator iterator()     returns an iterator.
 Iterator it=collectionname.iterator();

 9)public Object[] toArray()   converts collection into array.
 Object[] arrayname=collectionname.toArray();
 10)public boolean isEmpty()         checks if collection is empty.
 11)public boolean equals(Object element)    matches two collection.
 boolean b5=collectionelement.equals("element")
 12) public boolean retainAll(Collection<?> c): It is used to delete all the elements of invoking collection except the
 specified collection

 Iterator interface:


Iterator interface provides the facility of iterating the elements in forward direction only.
Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

public boolean hasNext() it returns true if iterator has more elements.
Iterator   it=collectionname.iterator();
while(it.hasNext()){
SOP(it.next());
}
public object next() it returns the element and moves the cursor pointer to the next element

LIST Interface:

List Interface is the subinterface of Collection. It contains index-based methods to insert, access and delete elements. It is a factory of ListIterator interface.

List Interface declaration

  1. public interface List<E> extends Collection<E>  

MethodDescription
void add(int index, E element)It is used to insert the specified element at the specified position in a list.
boolean add(E e)It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> c)It is used to append all of the elements in the specified collection to the end of a list.
boolean addAll(int index, Collection<? extends E> c)It is used to append all the elements in the specified collection, starting at the specified position of the list.
void clear()It is used to remove all of the elements from this list.
boolean equals(Object o)It is used to compare the specified object with the elements of a list.
int hashcode()It is used to return the hash code value for a list.
E get(int index)It is used to fetch the element from the particular position of the list.
boolean isEmpty()It returns true if the list is empty, otherwise false.
int lastIndexOf(Object o)It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Object[] toArray()It is used to return an array containing all of the elements in this list in the correct order.
T[] toArray(T[] a)It is used to return an array containing all of the elements in this list in the correct order.
boolean contains(Object o)It returns true if the list contains the specified element
boolean containsAll(Collection<?> c)It returns true if the list contains all the specified element
int indexOf(Object o)It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
E remove(int index)It is used to remove the element present at the specified position in the list.
boolean remove(Object o)It is used to remove the first occurrence of the specified element.
boolean removeAll(Collection<?> c)It is used to remove all the elements from the list.
void replaceAll(UnaryOperator operator)It is used to replace all the elements from the list with the specified element.
void retainAll(Collection<?> c)It is used to retain all the elements in the list that are present in the specified collection.
E set(int index, E element)It is used to replace the specified element in the list, present at the specified position.
void sort(Comparator<? super E> c)It is used to sort the elements of the list on the basis of specified comparator.
Spliterator spliterator()It is used to create spliterator over the elements in a list.
List<E> subList(int fromIndex, int toIndex)It is used to fetch all the elements lies within the given range.
int size()It is used to return the number of elements present in the list.

Java ListIterator Interface

ListIterator Interface is used to traverse the element in a backward and forward direction.

ListIterator Interface declaration

  1. public interface ListIterator<E> extends Iterator<E>  

Methods of Java ListIterator Interface:

MethodDescription
void add(E e)This method inserts the specified element into the list.
boolean hasNext()This method returns true if the list iterator has more elements while traversing the list in the forward direction.
E next()This method returns the next element in the list and advances the cursor position.
int nextIndex()This method returns the index of the element that would be returned by a subsequent call to next()
boolean hasPrevious()This method returns true if this list iterator has more elements while traversing the list in the reverse direction.
E previous()This method returns the previous element in the list and moves the cursor position backward.
E previousIndex()This method returns the index of the element that would be returned by a subsequent call to previous().
void remove()This method removes the last element from the list that was returned by next() or previous() methods
void set(E e)This method replaces the last element returned by next() or previous() methods with the specified element.


Java ArrayList class:

Java ArrayList class hierarchyJava ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.
The important points about Java ArrayList class are:
  • Java ArrayList class can contain duplicate elements.
  • Java ArrayList class maintains insertion order.
  • Java ArrayList class is non synchronized.
  • Java ArrayList allows random access because array works at the index basis.
  • In Java ArrayList class, manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list

Hierarchy of ArrayList class:

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable  

Constructors of Java ArrayList

ConstructorDescription
ArrayList()It is used to build an empty array list.
ArrayList(Collection<? extends E> c)It is used to build an array list that is initialized with the elements of the collection c.
ArrayList(int capacity)It is used to build an array list that has the specified initial capacity.



Methods of Java ArrayList

MethodDescription
void add(int index, E element)It is used to insert the specified element at the specified position in a list.
boolean add(E e)It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> c)It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.
boolean addAll(int index, Collection<? extends E> c)It is used to append all the elements in the specified collection, starting at the specified position of the list.
void clear()It is used to remove all of the elements from this list.
void ensureCapacity(int requiredCapacity)It is used to enhance the capacity of an ArrayList instance.
E get(int index)It is used to fetch the element from the particular position of the list.
boolean isEmpty()It returns true if the list is empty, otherwise false.
int lastIndexOf(Object o)It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
Object[] toArray()It is used to return an array containing all of the elements in this list in the correct order.
<T> T[] toArray(T[] a)It is used to return an array containing all of the elements in this list in the correct order.
Object clone()It is used to return a shallow copy of an ArrayList.
boolean contains(Object o)It returns true if the list contains the specified element
int indexOf(Object o)It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
E remove(int index)It is used to remove the element present at the specified position in the list.
boolean remove(Object o)It is used to remove the first occurrence of the specified element.
boolean removeAll(Collection<?> c)It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E> filter)It is used to remove all the elements from the list that satisfies the given predicate.
protected void removeRange(int fromIndex, int toIndex)It is used to remove all the elements lies within the given range.
void replaceAll(UnaryOperator<E> operator)It is used to replace all the elements from the list with the specified element.
void retainAll(Collection<?> c)It is used to retain all the elements in the list that are present in the specified collection.
E set(int index, E element)It is used to replace the specified element in the list, present at the specified position.
void sort(Comparator<? super E> c)It is used to sort the elements of the list on the basis of specified comparator.
Spliterator<E> spliterator()It is used to create spliterator over the elements in a list.
List<E> subList(int fromIndex, int toIndex)It is used to fetch all the elements lies within the given range.
int size()It is used to return the number of elements present in the list.
void trimToSize()It is used to trim the capacity of this ArrayList instance to be the list's current size.
Why do you use Array when ArrayList is available?
ChatGPT

The choice between using an array or an ArrayList (or similar dynamic array-like data structure) depends on the specific requirements and constraints of your programming task. Both arrays and ArrayLists have their advantages and trade-offs, and the decision should be based on the context of your application.

Here are some considerations for when to use each:

Use Arrays When:

  1. Fixed Size: Arrays have a fixed size once they are created. If you know the size of the data you need to store and it won't change, arrays can be more memory-efficient and slightly faster than dynamic data structures like ArrayList. This is because arrays don't need to dynamically allocate memory.

  2. Performance-Critical Applications: In performance-critical applications, where every CPU cycle and memory allocation matters, arrays can offer better performance because they have less overhead compared to dynamic data structures like ArrayList.

  3. Primitive Types: Arrays are ideal for storing primitive data types (e.g., int, double, char) because they don't require boxing and unboxing, which can occur when storing these types in an ArrayList.

Use ArrayList When:

  1. Dynamic Sizing: ArrayLists dynamically resize themselves as needed. If you don't know the size of your data in advance or if it may change over time, ArrayLists are more flexible and convenient.

  2. Simpler APIs: ArrayLists provide a more user-friendly and feature-rich API compared to arrays. They have built-in methods for adding, removing, and manipulating elements, making your code more readable and maintainable.

  3. Generics: ArrayLists can store generic types, which provides type safety and avoids the need for explicit casting when retrieving elements.

  4. Collections Framework Integration: If you're working with Java's Collections Framework, which includes classes like List, Set, and Map, using ArrayList is often more seamless because it implements the List interface.

  5. Interoperability: ArrayLists can be easily converted to arrays using the toArray method, providing compatibility when working with APIs that require arrays.

In summary, the choice between using an array or an ArrayList depends on factors such as your application's requirements, performance considerations, the flexibility needed for dynamic data, and the convenience of the provided APIs. Each has its own strengths, and it's important to choose the data structure that best fits your specific use case

LinkedinList:

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

  • Java LinkedList class can contain duplicate elements.
  • Java LinkedList class maintains insertion order.
  • Java LinkedList class is non synchronized.
  • In Java LinkedList class, manipulation is fast because no shifting needs to occur.
  • Java LinkedList class can be used as a list, stack or queue

Doubly Linked List:

In the case of a doubly linked list, we can add or remove elements from both sides.
java LinkedList class using doubly linked list

Hierarchy of LinkedList class:

public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, Serializable 


Constructors of Java LinkedList

ConstructorDescription
LinkedList()It is used to construct an empty list.
LinkedList(Collection<? extends E> c)It is used to construct a list containing the elements of the specified collection, in the order, they are returned by the collection's iterator.

Methods of Java LinkedList

MethodDescription
boolean add(E e)It is used to append the specified element to the end of a list.
void add(int index, E element)It is used to insert the specified element at the specified position index in a list.
boolean addAll(Collection<? extends E> c)It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.
boolean addAll(Collection<? extends E> c)It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.
boolean addAll(int index, Collection<? extends E> c)It is used to append all the elements in the specified collection, starting at the specified position of the list.
void addFirst(E e)It is used to insert the given element at the beginning of a list.
void addLast(E e)It is used to append the given element to the end of a list.
void clear()It is used to remove all the elements from a list.
Object clone()It is used to return a shallow copy of an ArrayList.
boolean contains(Object o)It is used to return true if a list contains a specified element.
Iterator<E> descendingIterator()It is used to return an iterator over the elements in a deque in reverse sequential order.
E element()It is used to retrieve the first element of a list.
E get(int index)It is used to return the element at the specified position in a list.
E getFirst()It is used to return the first element in a list.
E getLast()It is used to return the last element in a list.
int indexOf(Object o)It is used to return the index in a list of the first occurrence of the specified element, or -1 if the list does not contain any element.
int lastIndexOf(Object o)It is used to return the index in a list of the last occurrence of the specified element, or -1 if the list does not contain any element.
ListIterator<E> listIterator(int index)It is used to return a list-iterator of the elements in proper sequence, starting at the specified position in the list.
boolean offer(E e)It adds the specified element as the last element of a list.
boolean offerFirst(E e)It inserts the specified element at the front of a list.
boolean offerLast(E e)It inserts the specified element at the end of a list.
E peek()It retrieves the first element of a list
E peekFirst()It retrieves the first element of a list or returns null if a list is empty.
E peekLast()It retrieves the last element of a list or returns null if a list is empty.
E poll()It retrieves and removes the first element of a list.
E pollFirst()It retrieves and removes the first element of a list, or returns null if a list is empty.
E pollLast()It retrieves and removes the last element of a list, or returns null if a list is empty.
E pop()It pops an element from the stack represented by a list.
void push(E e)It pushes an element onto the stack represented by a list.
E remove()It is used to retrieve and removes the first element of a list.
E remove(int index)It is used to remove the element at the specified position in a list.
boolean remove(Object o)It is used to remove the first occurrence of the specified element in a list.
E removeFirst()It removes and returns the first element from a list.
boolean removeFirstOccurrence(Object o)It is used to remove the first occurrence of the specified element in a list (when traversing the list from head to tail).
E removeLast()It removes and returns the last element from a list.
boolean removeLastOccurrence(Object o)It removes the last occurrence of the specified element in a list (when traversing the list from head to tail).
E set(int index, E element)It replaces the element at the specified position in a list with the specified element.
Object[] toArray()It is used to return an array containing all the elements in a list in proper sequence (from first to the last element).
<T> T[] toArray(T[] a)It returns an array containing all the elements in the proper sequence (from first to the last element); the runtime type of the returned array is that of the specified array.
int size()It is used to return the number of elements in a list.

Vector:

Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It is synchronized and contains many methods that are not the part of Collection framework.

Stack:

The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack. The stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.

Stack Methods

  1. push(element):

    • Purpose: Adds an element to the top of the stack.

Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
System.out.println(stack); // Output: [10, 20]

pop():

  • Purpose: Removes and returns the top element of the stack. If the stack is empty, this method usually throws an exception (like EmptyStackException in Java).
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
int top = stack.pop();
System.out.println(top); // Output: 20
System.out.println(stack); // Output: [10]

peek():
Purpose: Returns the top element of the stack without removing it. If the stack is empty, this method usually throws an exception.
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
int top = stack.peek();
System.out.println(top); // Output: 20
System.out.println(stack); // Output: [10, 20]
==============================================================

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        // Push elements to the stack
        stack.push(10);
        stack.push(20);
        stack.push(30);

        // Peek at the top element
        System.out.println("Top element is: " + stack.peek()); // Output: 30

        // Pop the top element
        System.out.println("Popped element is: " + stack.pop()); // Output: 30

        // Peek at the top element again
        System.out.println("Top element is: " + stack.peek()); // Output: 20

        // Pop the remaining elements
        System.out.println("Popped element is: " + stack.pop()); // Output: 20
        System.out.println("Popped element is: " + stack.pop()); // Output: 10
    }
}
--------------------------------------------------------------------------------------------------------------------------

Queue Interface:

Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold the elements which are about to be processed. There are various classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.

Difference between the ArrayList & LinkedinList:

ArrayList and LinkedList both implements List interface and maintains insertion order. Both are non synchronized classes.
However, there are many differences between ArrayList and LinkedList classes that are given below.

ArrayListLinkedList
1) ArrayList internally uses a dynamic array to store the elements.LinkedList internally uses a doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory.Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
3) An ArrayList class can act as a list only because it implements List only.LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data.LinkedList is better for manipulating data.

Java Non-generic Vs. Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.
Java new generic collection allows you to have only one type of object in a collection. Now it is type safe so typecasting is not required at runtime.
  • Stronger type checks at compile time.
    A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

  • Elimination of casts.
    The following code snippet without generics requires casting:
    List list = new ArrayList();
    list.add("hello");
    String s = (String) list.get(0);
    
    When re-written to use generics, the code does not require casting:
    List<String> list = new ArrayList<String>();
    list.add("hello");
    String s = list.get(0);   // no cast
    
  • Enabling programmers to implement generic algorithms
Let's see the old non-generic example of creating java collection.
  1. ArrayList al=new ArrayList();//creating old non-generic arraylist  
Let's see the new generic example of creating java collection.
  1. ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist  
In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have the only specified type of objects in it. If you try to add another type of object, it gives compile time error.
List<datatype>collectionname=webdriverpluralmethods();
List collectionName=new ArrayList()ànon generic format
List<datatype>collectionname=new ArrayList<datatype>();  //generic format
Set<datatype>collectionname=webdriverpluralmethods();
//Set<datatype>collectionname=new implentingclass<datatype>();
Set<datatype>collectionname=new HashSet/LinkedHashSet/TreeSet<datatype>();   ///Generic Format 

Set Interface:

Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the unordered set of elements which doesn't allow us to store the duplicate items. We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.
Set can be instantiated as:
  1. Set<data-type> s1 = new HashSet<data-type>();  
  2. Set<data-type> s2 = new LinkedHashSet<data-type>();  
  3. Set<data-type> s3 = new TreeSet<data-type>(); 


Java HashSet

Java HashSet class hierarchy
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface.
The important points about Java HashSet class are:
  • HashSet stores the elements by using a mechanism called hashing.
  • HashSet contains unique elements only.
  • HashSet allows null value.
  • HashSet class is non synchronized.
  • HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
  • HashSet is the best approach for search operations.
  • The initial default capacity of HashSet is 16, and the load factor is 0.75.

HashSet class declaration

java.util.HashSet class.
  1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Constructors of Java HashSet class

SNConstructorDescription
1)HashSet()It is used to construct a default HashSet.
2)HashSet(int capacity)It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
3)HashSet(int capacity, float loadFactor)It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor.
4)HashSet(Collection<? extends E> c)It is used to initialize the hash set by using the elements of the collection c.

Methods of Java HashSet class

Various methods of Java HashSet class are as follows:
SNModifier & TypeMethodDescription
1)booleanadd(E e)It is used to add the specified element to this set if it is not already present.
2)voidclear()It is used to remove all of the elements from the set.
3)objectclone()It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
4)booleancontains(Object o)It is used to return true if this set contains the specified element.
5)booleanisEmpty()It is used to return true if this set contains no elements.
6)Iterator<E>iterator()It is used to return an iterator over the elements in this set.
7)booleanremove(Object o)It is used to remove the specified element from this set if it is present.
8)intsize()It is used to return the number of elements in the set.
9)Spliterator<E>spliterator()It is used to create a late-binding and fail-fast Spliterator over the elements in the set.


LinkedHashSet:

LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits null elements.

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

Convert Set into List:

List<String>list=new ArrayList<String>(set);

Covert List into Set collection:
Set<datatype>collectioName=new HashSet<datatype>(listCollectionName);

Difference between List and Set:


  • A list can contain duplicate elements whereas Set contains unique elements only.
  • List is ordered collection where as Set is UnOrdered Collection
  • List Elements cane be accessed uisng Index. Whereas Set collection elements cannot be accessed using index
  • List is implemented by ArrayList,LinkedinList & Vector where as Set is implemented by HashSet,LinkedinHashSet & treeSet classes

Difference between Iterator and ListIterator?

  • Iterator can traverse in forward direction only whereas  ListIterator can be used to traverse in both directions.
  • ListIterator inherits from Iterator interface and comes with extra functions like adding an
  • element,replacing an element,getting index position for previous and next elements
  • We can use Iterator to traverse Set and List collections whereas ListIterator can be used with Lists only

How to Iterate Collection:

1)By Iterator interface.
Iterator  it=collectionname.iterator();
While(it.hasNext()){
System.out.println(it.next());
}

2)By for-each loop.
//for(datatype varaiblename:collectionname){statements+logic}

3)By normal for loop
for(initialization;condition;increment/decrement){statements+logic}

EXERCISES:
1. Write a Java program to create a new array list, add some colors (string) and print out the collection.
2)Write a Java program to iterate through all elements in a array list.
3) Write a Java program to insert an element into the array list at the first position
4)Write a Java program to retrieve an element (at a specified index) from a given array list
5)Write a Java program to update specific arraylist element by given element.
6)Write a Java program to remove the third element from a array list.
7)Write a Java program to search an element in a array list
8)Write a Java program to sort a given array list.
9)Write a Java program to copy one array list into another
10)Write a Java program to empty an array list
11)Write a Java program to test an array list is empty or not
-----------------------------------------------------------------------------------------------
Interview Program 1)
Write a program to arrange even numbers at the beginning and then odd numbers of the
* given array int[] arr={1,2,5,4,7,8,11,20};
Hint:Use ArrayList methods add() and addAll()
-----------------------------------------------------------------------------------------------
Interview Program 2)
Write a java program to print union of two array elements and common elements from two given arrays
int[] arr1= {80,10,15,2,35,60};
int[] arr2= {35,80,60,20,75};
Hint: Create HashSet
2)iterate first array and add all the elements to set collection
3)iterate second array and add all the elements to set collection
4)Then print the set collection for union elements

PartII) Common elements from both the Arrays
1)create a hashset
2)iterate first array and add all the elements to set collection
3)iterate the second array and check array element is present in set collection then print that array element
----------------------------------------------------------------------
INTRVIEW EXERCISE3)
Write a program to find duplicate elements in given array
int[] arr= {2,1,3,5,3,2};
Hint) 1)Create Set Collection
2)Iterate the array and check HashSet contains array element using contains() if true print the arrayelement
--------------------------------------------------------------
Problem Description Given a matrix, A of size M x N of 0s and 1s. If an element is 0, set its entire row and column to 0. Note: This will be evaluated on the extra memory used. Try to minimize the space and time complexity. Problem Constraints 1 <= N, M <= 1000 0 <= A[i][j] <= 1 Input Format The first and the only argument of input contains a 2-d integer matrix, A, of size M x N. Output Format Return a 2-d matrix that satisfies the given conditions. Example Input Input 1: [ [1, 0, 1], [1, 1, 1], [1, 1, 1] ] Input 2: [ [1, 0, 1], [1, 1, 1], [1, 0, 1] ] Example Output Output 1: [ [0, 0, 0], [1, 0, 1], [1, 0, 1] ] Output 2: [ [0, 0, 0], [1, 0, 1], [0, 0, 0] ]
import java.util.HashSet;
import java.util.Set;

public class Solution {
    public int[][] setZeroes(int[][] A) {
        Set<Integer> rows = new HashSet<>();
        Set<Integer> cols = new HashSet<>();

        // Find rows and columns with zeros
        for (int i = 0; i < A.length; i++) {
            for (int j = 0; j < A[0].length; j++) {
                if (A[i][j] == 0) {
                    rows.add(i);
                    cols.add(j);
                }
            }
        }

        // Set zeros for rows
        for (int i : rows) {
            for (int j = 0; j < A[0].length; j++) {
                A[i][j] = 0;
            }
        }

        // Set zeros for columns
        for (int j : cols) {
            for (int i = 0; i < A.length; i++) {
                A[i][j] = 0;
            }
        }

        return A;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] A1 = {
                {1, 0, 1},
                {1, 1, 1},
                {1, 1, 1}
        };
        int[][] A2 = {
                {1, 0, 1},
                {1, 1, 1},
                {1, 0, 1}
        };

        int[][] result1 = solution.setZeroes(A1);
        int[][] result2 = solution.setZeroes(A2);

        System.out.println("Output 1:");
        for (int[] row : result1) {
            for (int cell : row) {
                System.out.print(cell + " ");
            }
            System.out.println();
        }

        System.out.println("Output 2:");
        for (int[] row : result2) {
            for (int cell : row) {
                System.out.print(cell + " ");
            }
            System.out.println();
        }
    }
}
=======================================================



---------------------

Java Map Interface:
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.

Java Map Hierarchy

There are two interfaces for implementing Map in java: Map and SortedMap, and three classes: HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:

Java Map Hierarchy
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.
A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.
ClassDescription
HashMapHashMap is the implementation of Map, but it doesn't maintain any order.
LinkedHashMapLinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order.
TreeMapTreeMap is the implementation of Map and SortedMap. It maintains ascending order.

Useful methods of Map interface

MethodDescription
V put(Object key, Object value)It is used to insert an entry in the map.
void putAll(Map map)It is used to insert the specified map in the map.
V putIfAbsent(K key, V value)It inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key)It is used to delete an entry for the specified key.
boolean remove(Object key, Object value)It removes the specified values with the associated specified keys from the map.
Set keySet()It returns the Set view containing all the keys.
Set<Map.Entry<K,V>> entrySet()It returns the Set view containing all the keys and values.
void clear()It is used to reset the map.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value)This method returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key)This method returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o)It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? super V> action)It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key)This method returns the object that contains the value associated with the key.
V getOrDefault(Object key, V defaultValue)It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
int hashCode()It returns the hash code value for the Map
boolean isEmpty()This method returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V replace(K key, V value)It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue)It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection values()It returns a collection view of the values contained in the map.
int size()This method returns the number of entries in the map.

Map.Entry Interface:Entry is the subinterface of Map. So we will be accessed it by Map.Entry name. It returns a collection-view of the map, whose elements are of this class. It provides methods to get key and value.

Methods of Map.Entry interface

MethodDescription
K getKey()It is used to obtain a key.
V getValue()It is used to obtain value.
int hashCode()It is used to obtain hashCode.

Java HashMap class

Java HashMap class hierarchy
Java HashMap class implements the map interface by using a hash table. It inherits AbstractMap class and implements Map interface.

Points to remember

  • Java HashMap class contains values based on the key.
  • Java HashMap class contains only unique keys.
  • Java HashMap class may have one null key and multiple null values.
  • Java HashMap class is non synchronized.
  • Java HashMap class maintains no order.
  • The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.

Hierarchy of HashMap class

As shown in the above figure, HashMap class extends AbstractMap class and implements Map interface.

HashMap class declaration

Let's see the declaration for java.util.HashMap class.
  1. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable  

HashMap class Parameters

Let's see the Parameters for java.util.HashMap class.
  • K: It is the type of keys maintained by this map.
  • V: It is the type of mapped values.

Constructors of Java HashMap class

ConstructorDescription
HashMap()It is used to construct a default HashMap.
HashMap(Map<? extends K,? extends V> m)It is used to initialize the hash map by using the elements of the given Map object m.
HashMap(int capacity)It is used to initializes the capacity of the hash map to the given integer value, capacity.
HashMap(int capacity, float loadFactor)It is used to initialize both the capacity and load factor of the hash map by using its arguments.

Methods of Java HashMap class

MethodDescription
void clear()It is used to remove all of the mappings from this map.
boolean isEmpty()It is used to return true if this map contains no key-value mappings.
Object clone()It is used to return a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
Set entrySet()It is used to return a collection view of the mappings contained in this map.
Set keySet()It is used to return a set view of the keys contained in this map.
V put(Object key, Object value)It is used to insert an entry in the map.
void putAll(Map map)It is used to insert the specified map in the map.
V putIfAbsent(K key, V value)It inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key)It is used to delete an entry for the specified key.
boolean remove(Object key, Object value)It removes the specified values with the associated specified keys from the map.
V compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)It is used to compute its value using the given mapping function, if the specified key is not already associated with a value (or is mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)It is used to compute a new mapping given the key and its current mapped value if the value for the specified key is present and non-null.
boolean containsValue(Object value)This method returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key)This method returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o)It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? super V> action)It performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
V get(Object key)This method returns the object that contains the value associated with the key.
V getOrDefault(Object key, V defaultValue)It returns the value to which the specified key is mapped, or defaultValue if the map contains no mapping for the key.
boolean isEmpty()This method returns true if the map is empty; returns false if it contains at least one key.
V merge(K key, V value, BiFunction<? super V,? super V,? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
V replace(K key, V value)It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V newValue)It replaces the old value with the new value for a specified key.
void replaceAll(BiFunction<? super K,? super V,? extends V> function)It replaces each entry's value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.
Collection<V> values()It returns a collection view of the values contained in the map.
int size()This method returns the number of entries in the map.

If hashmap is available then why do you need HashSet?

HashMap and HashSet serve different purposes and have distinct use cases, even though they both use hash-based data structures.

Here's a brief explanation of each and when you might choose one over the other:

  1. HashMap:

    • A HashMap is a key-value data structure that allows you to store and retrieve values associated with unique keys.
    • It associates each key with a specific value, making it suitable for mapping relationships between keys and values.
    • Common use cases for HashMap include storing configuration settings, caching, and representing relationships in data structures like graphs (using adjacency lists).
    • When you need to associate values with specific identifiers or keys, HashMap is a good choice.

    Example in Java:

    java
    Map<String, Integer> ageMap = new HashMap<>(); ageMap.put("Alice"25); ageMap.put("Bob"30); int aliceAge = ageMap.get("Alice"); // Retrieves the age of A

HashSet:

  • A HashSet is an unordered collection of unique elements, typically used to ensure that a collection contains no duplicate values.
  • It is often used when you want to check for the presence of an element in a collection without regard to its position.
  • Common use cases for HashSet include implementing sets and ensuring uniqueness in a collection of items.
  • When you need to maintain a collection of unique elements or efficiently check for the presence of an element, HashSet is a suitable choice.

Example in Java:

Set<String> uniqueNames = new HashSet<>(); uniqueNames.add("Alice"); uniqueNames.add("Bob"); boolean containsAlice = uniqueNames.contains("Alice"); // Checks if "Alice" is in the set

In summary, while both HashMap and HashSet use hash-based data structures, they have different purposes. HashMap is used for mapping keys to values, while HashSet is used for maintaining collections of unique elements. The choice between them depends on the specific requirements of your data and the operations you need to perform.

HOW HASHMAP WORKS INTERNALLY?





linkedlist stores the data in the form of buckets. Bucket is nothing but linkedlist.
in Linkedinlist one node pointing to the other node



JVM will take the put method key value and calculate the hashcode of key and then in step2 find the index of that hashcode



suppose take one more key value pair

Lets visualize the bucket storage
Lets take one more data set that teaches the hash collision. The bucket is having already one node and again jvm tries to place one more node in same bucket that is called hash collision


JVM  checks if same key is present in the bucket or not using equals() if same key is present then jvm will update the existing key with new value.


if the existing key is not equal to new one then new data will be added  to the same linkedlist as second node now you an observe that linkedlist is growing

Summary of entire put("key","value") method 

How Searching will happen in linkedlist is one by one node will search that is the drawback of linkedlist. It reduces the performance



How we will get key value in HashMap describes below picture


Interview Question)
 18) When int a = 20; 
int b = a ;  
System.out.println(a); -> o/p - 20
System.out.println(b); -> o/p - 20
a=30; 
System.out.println(a); -> o/p - 30
System.out.println(b); -> o/p - 20

But when we do same operation in HashMaps

Map<String, Integer> map1 = new HashMap<>();
map1.put(“value”, 25);

Map<String, Integer> map2 = new HashMap<>();

map1=map2;

System.out.println(map1); -> o/p - value,25
System.out.println(map2); -> o/p - 20 - value,25

Now if we update this to - 
map1.put(“value”, 42)

System.out.println(map1); -> o/p - value,42
System.out.println(map2); -> o/p - 20 - value,42

Why does this happen??

Ans)
n the code you provided, there is a key misunderstanding about how objects and references work in Java, especially when it comes to collections like HashMap. Let's break down the behavior step by step
  1. Initially, you create two HashMap instances, map1 and map2.
  2. You put a key-value pair ("value", 25) into map1.
  3. Then, you make map1 reference the same object as map2. This means both map1 and map2 now refer to the same HashMap object, effectively discarding the original map1.
  4. When you print map1 and map2, they both refer to the same HashMap object, so you see the same content ("value", 25).

Now, let's look at the update:

  1. You update the map1 by putting a new key-value pair ("value", 42). Since map1 and map2 both reference the same HashMap object, the change is reflected in both references.
  2. When you print map1 and map2 again, they both reference the same updated HashMap object, so you see the updated content ("value", 42).

This behavior is because map1 and map2 are references to the same HashMap object in memory. Changing the content through one reference affects the object, and any other references to that object will see the changes.

In contrast, in your initial example with integers (int), you are dealing with primitive data types. When you assign b = a, you are making a copy of the value of a. Changing a afterward does not affect b because b holds a separate copy of the value. This is different from reference types like HashMap, where the references point to the same object in memory.

=====================================

Difference between HashMap and Hashtable

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
HashMapHashtable
1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.Hashtable is synchronized. It is thread-safe and can be shared with many threads.
2) HashMap allows one null key and multiple null values.Hashtable doesn't allow any null key or value.
3) HashMap is a new class introduced in JDK 1.2.Hashtable is a legacy class.
4) HashMap is fast.Hashtable is slow.
5) We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can't be unsynchronized.
6) HashMap is traversed by Iterator.Hashtable is traversed by Enumerator and Iterator.
7) Iterator in HashMap is fail-fast.Enumerator in Hashtable is not fail-fast.
8) HashMap inherits AbstractMap class.Hashtable inherits Dictionary class.

Sorting in Collection

We can sort the elements of:
  1. String objects
  2. Wrapper class objects
  3. User-defined class objects
Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List. List elements must be of the Comparable type.

Note: String class and Wrapper classes implement the Comparable interface. So if you store the objects of string or wrapper classes, it will be Comparable

Java Comparable interface

Java Comparable interface is used to order the objects of the user-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only. For example, it may be rollno, name, age or anything else.

compareTo(Object obj) method

public int compareTo(Object obj): It is used to compare the current object with the specified object. It returns
  • positive integer, if the current object is greater than the specified object.
  • negative integer, if the current object is less than the specified object.
  • zero, if the current object is equal to the specified object.

Java Comparator interface

Java Comparator interface is used to order the objects of a user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data member, for example, rollno, name, age or anything else.

Methods of Java Comparator Interface

MethodDescription
public int compare(Object obj1, Object obj2)It compares the first object with the second object.
public boolean equals(Object obj)It is used to compare the current object with the specified object.
public boolean equals(Object obj)It is used to compare the current object with the specified object.

Collections class

Collections class provides static methods for sorting the elements of a collection. If collection elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements also.

Method of Collections class for sorting List elements

public void sort(List list, Comparator c): is used to sort the elements of List by the given Comparator

Difference between Comparable and Comparator

Comparable and Comparator both are interfaces and can be used to sort collection elements.
However, there are many differences between Comparable and Comparator interfaces that are given below.
ComparableComparator
1) Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price.The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc.
2) Comparable affects the original class, i.e., the actual class is modified.Comparator doesn't affect the original class, i.e., the actual class is not modified.
3) Comparable provides compareTo() method to sort elements.Comparator provides compare() method to sort elements.
4) Comparable is present in java.lang package.A Comparator is present in the java.util package.
5) We can sort the list elements of Comparable type by Collections.sort(List) method.We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.

Difference between ArrayList and Vector

ArrayList and Vector both implements List interface and maintains insertion order.
However, there are many differences between ArrayList and Vector classes that are given below.
ArrayListVector
1) ArrayList is not synchronized.Vector is synchronized.
2) ArrayList increments 50% of current array size if the number of elements exceeds from its capacity.Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity.
3) ArrayList is not a legacy class. It is introduced in JDK 1.2.Vector is a legacy class.
4) ArrayList is fast because it is non-synchronized.Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object.
5) ArrayList uses the Iterator interface to traverse the elements.A Vector can use the Iterator interface or Enumeration interface to traverse the elements.

================================================

Differences between Collection and Collections

----------------------------------------------------------------------------------------
Below are the few difference between the Collection(framework), Collections class.

1. Collection is an interface in Java. But Collections is a class in Java.
2. Collection is a base interface. Collections is a utility class in Java.
3. Collection defines methods that are used for data structures that contain the objects.
Collections defines the methods that are used for operations like access, find etc. on a
Collection.
4. Collection Interface has only abstract methods but Collections consists of only static methods
which are used to operate on objects of type Collection.
===========================================================

Arrays vs Collection

------------------------------------------------------------------------------------------------------
There are so many difference but I am highlighting whatever i know, so there is chance that more than these differences to be present between them.


1. Arrays are fixed in size but Collections are dynamic in size.
2. With respect to memory arrays are not good to use but with respect to memory
 Collections are better to use.
3. With respect to performance; it is better to use arrays but with respect to performance
collection are not good to use.
1.   Arrays can hold only homogeneous elements but collections can hold both homogeneous
and heterogeneous elements
5. Arrays don't have readymade methods but collections have readymade data structures and methods, which makes collections more user friendly
6. Arrays can hold both primitives and wrapper objects but collections can hold only objects.
7. ClassCasException occurs in Collection but not in Arrays
8. We have iterators for going through the collection but we donot have them for arrays
9. Java returns Arrays rather than Collection in most of the operations due to performance issues.

====================================

Properties class in Java

The properties object contains key and value pair both as a string. The java.util.Properties class is the subclass of Hashtable.
It can be used to get property value based on the property key. The Properties class provides methods to get data from the properties file and store data into the properties file. Moreover, it can be used to get the properties of a system.

An Advantage of the properties file

Recompilation is not required if the information is changed from a properties file: If any information is changed from the properties file, you don't need to recompile the java class. It is used to store information which is to be changed frequently.

Constructors of Properties class

MethodDescription
Properties()It creates an empty property list with no default values.
Properties(Properties defaults)It creates an empty property list with the specified defaults.

Methods of Properties class

The commonly used methods of Properties class are given below.
MethodDescription
public void load(Reader r)It loads data from the Reader object.
public void load(InputStream is)It loads data from the InputStream object
public void loadFromXML(InputStream in)It is used to load all of the properties represented by the XML document on the specified input stream into this properties table.
public String getProperty(String key)It returns value based on the key.
public String getProperty(String key, String defaultValue)It searches for the property with the specified key.
public void setProperty(String key, String value)It calls the put method of Hashtable.
public void list(PrintStream out)It is used to print the property list out to the specified output stream.
public void list(PrintWriter out))It is used to print the property list out to the specified output stream.
public Enumeration<?> propertyNames())It returns an enumeration of all the keys from the property list.
public Set<String> stringPropertyNames()It returns a set of keys in from property list where the key and its corresponding value are strings.
public void store(Writer w, String comment)It writes the properties in the writer object.
public void store(OutputStream os, String comment)It writes the properties in the OutputStream object.
public void storeToXML(OutputStream os, String comment)It writes the properties in the writer object for generating XML document.
public void storeToXML(Writer w, String comment, String encoding)It writes the properties in the writer object for generating XML document with the specified encoding.


Difference Between Collections Vs Streams In Java :

CollectionsStreams
Collections are mainly used to store and group the data.Streams are mainly used to perform operations on data.
You can add or remove elements from collections.You can’t add or remove elements from streams.
Collections have to be iterated externally.Streams are internally iterated.
Collections can be traversed multiple times.Streams are traversable only once.
Collections are eagerly constructed.Streams are lazily constructed.
Ex : List, Set, Map…Ex : filtering, mapping, matching…

Collections Programs:

1)ArrayList Demo program:

package collectionprograms;



import java.util.ArrayList;

import java.util.Arrays;

import java.util.Iterator;

import java.util.List;


public class ArrayListDemo {

public static void main(String[] args) {
// interface collectionname=new implementedclass();
List al=new ArrayList(); //non generic format
System.out.println("al collection is-->"+al);
System.out.println("al collection size is:"+al.size());
//add()--insert the element into collection
al.add("java");
al.add("ruby");
al.add(1, true);
System.out.println("al collection after add() is-->"+al);
System.out.println("al collection after add() size is:"+al.size());
//addAll()-->inserts the group of elements[collection] into collection
al.addAll(Arrays.asList("java","python",25,3.5F,'A'));
System.out.println("al collection after addAll() is-->"+al);
System.out.println("al collection after addAll() size is:"+al.size());
//remove()-->deletes the specified element from collection
al.remove(1);
System.out.println("al collection after remove() is-->"+al);
System.out.println("al collection after remove() size is:"+al.size());
//removeAll()-->collection of elements will be remvoed from collection
al.removeAll(Arrays.asList("ruby",25,3.5F));
System.out.println("al collection after removeAll() is-->"+al);
System.out.println("al collection after removeAll() size is:"+al.size());
al.addAll(1, Arrays.asList("selenium",50L,2345.678,'b'));
System.out.println("al collection after addAll() is-->"+al);
System.out.println("al collection after adAll() size is:"+al.size());
//isEmpty()
boolean b=al.isEmpty();
System.out.println("checking al collection is empty or not-->"+b);
//contains()-->search the given element is present in the collection or not
boolean b1=al.contains("selenium");
System.out.println("checking selenium in collection using contains()-->"+b1);
boolean b11=al.contains("webdriver");
System.out.println("checking webdriver in collection using contains()-->"+b11);
//containsAll()-->search collection of elements in the colelction
boolean b2=al.containsAll(Arrays.asList("java","python","selenium"));
System.out.println("checking selenium,java,python in collection using containsAll()-->"+b2);
//equals()--compares the givne element with collection element
boolean b3=al.get(0).equals("java");
System.out.println("comparing java with java using equals()-->"+b3);
//iterator()-->iterate the given colelction from first element to last element
Iterator it=al.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
System.out.println("************End of iterator()************************************");
//for(datatype variablename:colelctionaname){l+s}
for(Object a:al) {
System.out.println(a);
}
System.out.println("****************End of for each********************************");
for(int i=0;i<al.size();i++) {
System.out.println(al.get(i));
}
System.out.println("****************End of for ********************************");
//retainAll(collection c):retains specified collection of elements and removes other elements
al.retainAll(Arrays.asList("java","selenium","python",'A'));
System.out.println("al collection after retainAll()-->"+al);
System.out.println("al collection size after retainAll()-->"+al.size());
//clear()-->remvoes all the collection
al.clear();
System.out.println("al collection after clear()-->"+al);
System.out.println("al collection size after clear()-->"+al.size());
}

}

2)SetDemo Programs:
package collectionprograms;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class SetDemo {

public static void main(String[] args) {
   //interface<datatype>collectionname=new implemetedclass<datatype>();
//Set<String>hs=new HashSet<String>(); //generic format
//Set<String>hs=new LinkedHashSet<String>();
Set<String>hs=new TreeSet<String>();
System.out.println("set colelction -->"+hs);
System.out.println("set collection size is-->"+hs.size());
hs.add("bmw");
System.out.println("set colelction -->"+hs);
System.out.println("set collection size is-->"+hs.size());
hs.addAll(Arrays.asList("maruthi suzuki","ford","fiat","audi","cherokee","nissan","bmw","fiat"));
System.out.println("set colelction after addAll()-->"+hs);
System.out.println("set collection hs afert addAll() size is-->"+hs.size());
//iterate the set collection using iterator
Iterator<String>it=hs.iterator();
while(it.hasNext()) {
if(it.next().equals("bmw")) {
System.out.print(it.next()+"\t");
}
}
System.out.println();
System.out.println("*******************end of iterator method***********");
for(String h:hs) {
System.out.print(h+"\t");
}
System.out.println();
System.out.println("*******************end of for each***********");
//convert the set into list colelction
List<String>al=new ArrayList(hs);
System.out.println("al collection is-->"+al);
System.out.println("al collection size is-->"+al.size());
System.out.println("get the al collection 3rd element-->"+al.get(2));
//convert list into set collection
List<Integer>numbers=new ArrayList<Integer>();
numbers.addAll(Arrays.asList(5,6,1,3,5,10,15));
System.out.println("numbers list collection-->"+numbers);
System.out.println("numbers size is-->"+numbers.size());
System.out.println("Converting numbers list collection into set collection");
//Set<Integer>hs=new HashSet<integer>(listcollectionname);
Set<Integer>hsnumber=new HashSet<Integer>(numbers);
System.out.println("set collection is-->"+hsnumber);
System.out.println("set collection size is-->"+hsnumber.size());
}

}
==============================
Interview Programs on LIST:
----------------------------------------------------
package collectionprograms;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class InterviewPrograms {
/**
 * int[] arr={2,5,2,4,1,4,6}
 * @param arr
 * @return
 */
//accessmodifier datatype methodname(datatype p1){logic;return value;}
private List<Integer> removeDuplcateElementsUsingList(int[] arr){
System.out.println("array with duplicates:"+Arrays.toString(arr));
//create ArrayList object
List<Integer>resultantList=new ArrayList<>();
for(int i=0;i<arr.length;i++) {
if(!resultantList.contains(arr[i])) {
//add the unique element to lits
resultantList.add(arr[i]);
}
}
return resultantList;
}
private List<Integer> removeDuplicatesUsingSet(int[] arr){
System.out.println("array with duplicates:"+Arrays.toString(arr));
//create ArrayList object
List<Integer>resultantList=new ArrayList<>();
for(int i=0;i<arr.length;i++) {
//add the unique element to lits
resultantList.add(arr[i]);
}
System.out.println("before convertin ghte list into set:"+resultantList);
//convert the list into set
Set<Integer>setcol=new HashSet<Integer>(resultantList);
//convert the set into List colelction
List<Integer>finalList=new ArrayList<>(setcol);
return finalList;
}
public void reverseArrayListInPlace() {
//generic format of List
List<String>al=new ArrayList<String>();
al.addAll(Arrays.asList("Beans","Nuts","Soup","Dark Chacolate","Yogurt","pure Vegetables","Sausage"));
//                         0       1     2          3              4          5               6
System.out.println("before reverse originl collection:"+al);
System.out.println("al collection size:"+al.size());
int size=al.size();
//lets reverse the list in place
for(int i=0;i<size/2;i++) {//i=1 1<7-T|i=2|i=3 3<7/2-F
final String item=al.get(i); //Beans//Nuts|Soup
al.set(i, al.get(al.size()-i-1)); //0=Sausage//1=Pure Vegetables|2=Yogurt
al.set(size-i-1, item);//6=Beans//5=Nuts|4=Soup
}
System.out.println("after reverse in place arrayList:"+al);
}
public static void main(String[] args) {
int[] arr= {2,4,2,5,4,6,8,5};

//how can you call returntype nonstaticmethods?
/**
* create object for the class- InterviewPrograms using new keyword
* classname refobj=new classname();
*/
InterviewPrograms ipobj=new InterviewPrograms();
//how to call returntype nonstaticmethods
//datatype variablename=objectref.returntypenonstaticmethodname(inputvalue);
List<Integer> reslist=ipobj.removeDuplcateElementsUsingList(arr);
System.out.println("without diplicates arraylist is:"+reslist);
System.out.println("without duplicates using set collection:"+ipobj.removeDuplicatesUsingSet(arr));
ipobj.reverseArrayListInPlace();
}

}
---------------------------------------------
3)

Sets Union Intersection Difference and Complement

Union: Set of members that belong to the first set "or" the second set.

Intersection: Set of members that belong to the first set "and" the second set.

Difference: Set of members that belong to the first set "and not" the second set.

Complement: Set of members that belong to the second (universal) set "and not" the first set. 
Given the following sets:
 
   A={2,4,6,8,10}
   B={1,2,3,4,5}
 
   Union:        A∪B = {1,2,3,4,5,6,8,10}
   Intersection: A∩B = {2,4}
   Difference:   A-B = {6,8,10}
   Complement:   AB = {1,3,5}
import java.util.*;

public class Sets {

  public static void main(String args[]){

    Set<Integer> A = new HashSet<Integer>();
    A.addAll(Arrays.asList(2,4,6,8,10));

    Set<Integer> B = new HashSet<Integer>();
    B.addAll(Arrays.asList(1,2,3,4,5));

    /*
      Union: Set of members that belong to set A "or" set B.
    */
    Set<Integer> union = new HashSet<Integer>();
    union.addAll(A);
    union.addAll(B);

    /*
      Intersection: Set of members that belong to set A "and" set B.
    */
    Set<Integer> intersection = new HashSet<Integer>();
    intersection.addAll(A);
    intersection.retainAll(B);

    /*
      Difference: Set of members that belong set A "and not" set B.
    */
    Set<Integer> difference = new HashSet<Integer>();
    difference.addAll(A);
    difference.removeAll(B);

    /*
      Complement: Set of members that belong to set B "and not" set A.
    */
    Set<Integer> complement = new HashSet<Integer>();
    complement.addAll(B);
    complement.removeAll(A);

    System.out.println("A: " + A);
    System.out.println("B: " + B);
    System.out.println("union: " + union);
    System.out.println("intersection: " + intersection);
    System.out.println("difference: " + difference);
    System.out.println("complement: " + complement);

  }
}

4)MAP Programs:


package collectionprograms;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MapDemo {

public static void main(String[] args) {
//interface<k,v>mapname=new implementedclass<K,V>();
//Map<String,Integer>hm=new HashMap<String,Integer>();
// Map<String,Integer>hm=new LinkedHashMap<String,Integer>();
Map<String,Integer>hm=new TreeMap<String,Integer>();
System.out.println("Map hm is-->"+hm);
System.out.println("map hm size is-->"+hm.size());
//put(k,v)->insert the key value pair into map
hm.put("samsungmobile", 45000);
hm.put("motorola", 25000);
System.out.println("Map hm is-->"+hm);
System.out.println("map hm size is-->"+hm.size());
Map<String,Integer>hm1=new HashMap<String,Integer>();
hm1.put("oppo", 15000);
hm1.put("iphone", 50000);
//putAll():joins the two maps
hm.putAll(hm1);
System.out.println("Map hm is-->"+hm);
System.out.println("map hm size is-->"+hm.size());
//containsKey(k)->searches the specified key is present in the map or not
boolean b=hm.containsKey("oppo");
System.out.println("oppo is present in the map or not using containsKey()-->"+b);
boolean b1=hm.containsValue(50000);
System.out.println("50000 is present in the map or not using containsValue()-->"+b1);
//remove(key): deletes the entry from the map
hm.remove("oppo");
System.out.println("Map hm is-->"+hm);
System.out.println("map hm size is-->"+hm.size());
//get(key)-->it fetches the value of that key
System.out.println("iphone value is-->"+hm.get("iphone"));
//keySet()--returns Set collection fetches all keys in the map
Set<String>keyColl=hm.keySet();
Iterator<String> it=keyColl.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
System.out.println("************************************************");
//entrySet()--returns Set<Map.Entry<K,V>>
Set<Map.Entry<String, Integer>>entryCol=hm.entrySet();
for(Map.Entry<String, Integer> entry:entryCol) {
System.out.println("key name: "+entry.getKey()+" value is:"+entry.getValue());
}
}

}
------------------------------------------------------------------------------

How to Find the Occurrence of Each character in a given String:


package collectionprograms;



import java.util.HashMap;

import java.util.Map;

import java.util.Set;



public class StringProgramsWithMap {

// Selenium
private static void findOccurenceOfEachCharacter(String str) {
// 1 create a Map
Map<Character, Integer> hm = new HashMap<Character, Integer>();

// 2.convert the String into char[] using toCharArray();
char[] ch = str.toCharArray();
for (char c : ch) {
if (hm.containsKey(c)) {
hm.put(c, hm.get(c) + 1);
} else {
hm.put(c, 1);
}
}
System.out.println(hm);

}

public static void findDuplicateCharacters(String str) {
// 1 create a Map
Map<Character, Integer> hm = new HashMap<Character, Integer>();

// 2.convert the String into char[] using toCharArray();
char[] ch = str.toCharArray();
for (char c : ch) {
if (hm.containsKey(c)) {
hm.put(c, hm.get(c) + 1);
} else {
hm.put(c, 1);
}
}
//fetch only keys from map uisng keySet()
Set<Character>keysCol=hm.keySet();
for(Character k:keysCol) {
if(hm.get(k)>1) {
System.out.println("duplicate character is-->"+k);
}
}
}

public static void main(String[] args) {
findOccurenceOfEachCharacter("javaj2eejsp");
findDuplicateCharacters("javaj2eejsp");
}

}
=========================================
Properties programs:

first create a properties file under the project package
right click on any package-->new-->file-->filename.properties-->finish
Once you create a properties file. Enter data in properties file

#writing the data
#Sat Apr 25 08:14:22 IST 2020
uname=test@yopmail.com
url=http://linkedin.com
browser=edge
pwd=test123
dbname=testdb

Properties Reading and Writing program
package collectionprograms;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesDemo {
static String unameVal=null;
static String urlVal=null;
public static void main(String[] args) throws IOException {
//create object for Properties class
Properties prop=new Properties();
System.out.println(System.getProperty("user.dir"));
//read the properties file
try {
FileInputStream fis=new FileInputStream(System.getProperty("user.dir")+"\\src\\collectionprograms\\TestData.properties");
//load the properties
prop.load(fis);
System.out.println("browser valeu is-->"+prop.getProperty("browser"));
urlVal=prop.getProperty("url");
System.out.println("url value is-->"+urlVal);
unameVal=prop.getProperty("uname");
System.out.println("usern ame value is-->"+unameVal);
prop.setProperty("dbname", "testdb");
FileOutputStream fos=new FileOutputStream(System.getProperty("user.dir")+"\\src\\collectionprograms\\TestData.properties");
prop.store(fos, "writing the data");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

}
==============================================

Example to sort string objects

  1. import java.util.*;  
  2. class TestSort1{  
  3. public static void main(String args[]){  
  4.   
  5. ArrayList<String> al=new ArrayList<String>();  
  6. al.add("Viru");  
  7. al.add("Saurav");  
  8. al.add("Mukesh");  
  9. al.add("Tahir");  
  10.   
  11. Collections.sort(al);  
  12. Iterator itr=al.iterator();  
  13. while(itr.hasNext()){  
  14. System.out.println(itr.next());  
  15.  }  
  16. }  
  17. }  

Example to sort string objects in reverse order

  1. import java.util.*;  
  2. class TestSort2{  
  3. public static void main(String args[]){  
  4.   
  5. ArrayList<String> al=new ArrayList<String>();  
  6.         al.add("Viru");    
  7.         al.add("Saurav");    
  8.         al.add("Mukesh");    
  9.         al.add("Tahir");   
  10.           
  11.         Collections.sort(al,Collections.reverseOrder());  
  12.         Iterator i=al.iterator();  
  13.         while(i.hasNext())  
  14.         {  
  15.             System.out.println(i.next());  
  16.         }  
  17. }  
  18. }

Example to sort Wrapper class objects

  1. import java.util.*;  
  2. class TestSort3{  
  3. public static void main(String args[]){  
  4.   
  5. ArrayList al=new ArrayList();  
  6. al.add(Integer.valueOf(201));  
  7. al.add(Integer.valueOf(101));  
  8. al.add(230);//internally will be converted into objects as Integer.valueOf(230)  
  9.   
  10. Collections.sort(al);  
  11.   
  12. Iterator itr=al.iterator();  
  13. while(itr.hasNext()){  
  14. System.out.println(itr.next());  
  15.  }  
  16. }  
  17. }  

  18. ==============================================================
  19. Java Program to reverse an ArrayList in place

    Here is our sample Java program to reverse an ArrayList of String in place. The algorithm is generic, so you can also use it to reverse an ArrayList of Integer, Double, or any other object.

    import java.util.ArrayList;
    import java.util.List;
    
    /*
     * Java Program to reverse an ArrayList in place.
     * When you reverse ArrayList in place, you are not
     * allowed to use additional buffer e.g. an array
     * or any collection.
     */
    public class ReverseArrayListInPlace {
    
        public static void main(String args[]) {
    
            // Let's create a list of foods which helps
            // to lose weight, one of the prime concern programmers
            List<String> listOfFood = new ArrayList<>();
            listOfFood.add("Beans");
            listOfFood.add("Soup");
            listOfFood.add("Dark Chocolate");
            listOfFood.add("Yogurt");
            listOfFood.add("Sausage");
            listOfFood.add("Pure Vegetables");
            listOfFood.add("Nuts");
    
            System.out.println("Original ArrayList: " + listOfFood);
    
            // let's now reverse the list in place in Java
            int size = listOfFood.size();
            for (int i = 0; i < size / 2; i++) {
                final String food = listOfFood.get(i);
                listOfFood.set(i, listOfFood.get(size - i - 1)); // swap
                listOfFood.set(size - i - 1, food); // swap
            }
    
            System.out.println("Reversed ArrayList: " + listOfFood);
        }
    
    }
    
    Output:
    Original ArrayList: [Beans, Soup, Dark Chocolate, Yogurt, Sausage,
    Pure Vegetables, Nuts]
    Reversed ArrayList: [Nuts, Pure Vegetables, Sausage, Yogurt, Dark Chocolate,
    Soup, Beans]

  20. import java.io.*;
    import java.util.*;
    class RevArrayList {
     
        // Takes an arraylist as a parameter and returns
        // a reversed arraylist
        public ArrayList<Integer> reverseArrayList(ArrayList<Integer> alist)
        {
            // Arraylist for storing reversed elements
            // this.revArrayList = alist;
            for (int i = 0; i < alist.size() / 2; i++) {
                Integer temp = alist.get(i);
                alist.set(i, alist.get(alist.size() - i - 1));
                alist.set(alist.size() - i - 1, temp);
            }
     
            // Return the reversed arraylist
            return alist;
        }
  21. }

  22. =============================================
  23. find Max repeated character in given String
  24. String s="javaj2eejsp;
  25. Hints:1)//create a hashmap
  26. 2)
  27.         //convert the string into char[] using toCharArray() and replaceAllSpaces using replaceAll()
  28. 3//iterate the char array
  29. 4 //declare maxcount and maxChar variables
  30. 5)//fetch the entryset using entrySet() 
  31. 6)// Then iterate the set collection if(ent.getValue()>maxCount) then print count and char
  32. ===============
  33. PrintDuplicateOccurrencesOfString
  34. String str="i am am am java java coder"
  35. ================================================================================Guess the output on QUIZ
  36. 1)
  37. package collections;

  38. import java.util.IdentityHashMap;
  39. import java.util.Map;

  40. public class Test {
  41. static Map<String,String>hm = null;
  42. public static void main(String[] args) {
  43. hm = new IdentityHashMap<>();
  44. hm.put(new String("a"), "a");
  45. hm.put(new String("a"), "a");
  46. System.out.println(hm);
  47. }
  48. }
  49. i){a=a,a=a}
  50. ii){a=a}
  51. 2)



No comments:

Post a Comment

Note: Only a member of this blog may post a comment.