all questions
Sun May 26 2024 20:29:19 GMT+0000 (Coordinated Universal Time)
Saved by @prabhas
Write a java program to demonstrate the use of bounded type parameters and wild cards arguments. //BoundedType public class BoundedArithematic<T extends Number> { public double add(T a, T b) { return a.doubleValue() + b.doubleValue(); } public double subtract(T a, T b) { return a.doubleValue() - b.doubleValue(); } public double multiply(T a, T b) { return a.doubleValue() * b.doubleValue(); } public double divide(T a, T b) { if (b.doubleValue() == 0) { throw new ArithmeticException("Division by zero is not allowed."); } return a.doubleValue() / b.doubleValue(); } public static void main(String[] args) { BoundedArithematic<Number> calculator = new BoundedArithematic<>(); Integer a = 10; Integer b = 5; System.out.println("Addition: " + calculator.add(a, b)); System.out.println("Subtraction: " + calculator.subtract(a, b)); System.out.println("Multiplication: " + calculator.multiply(a, b)); System.out.println("Division: " + calculator.divide(a, b)); } } == //Wildcard Arguments public class MagicBox<T> { private T item; public void addItem(T item) { this.item = item; System.out.println("Added item to the magic box: " + item); } public T getItem() { return item; } public void processBox(MagicBox<? super Integer> box) { System.out.println("Items in the box are processed["+box.getItem()+"]"); } public static void main(String[] args) { MagicBox<Integer> integerBox = new MagicBox<>(); integerBox.addItem(43); MagicBox<String> stringBox = new MagicBox<>(); stringBox.addItem("Sofiya"); MagicBox<Boolean> booleanBox = new MagicBox<>(); booleanBox.addItem(false); MagicBox<Object> dobubleBox = new MagicBox<>(); dobubleBox.addItem(43.43); integerBox.processBox(integerBox); dobubleBox.processBox(dobubleBox); } } --------------------------------------------------------------------------------------------------------------------- 2.Write a java program that returns the value of pi using the lambda expression. public class PiLambdaExpression{ @FunctionalInterface interface PiValue{ double getPi(); } public static void main(String[] args) { PiValue pi = () -> Math.PI; double p= pi.getPi(); System.out.println("The value of Pi is: " + p); } } --------------------------------------------------------------------------------------------------------------------- 3. Write a java program that takes a string as parameter and calculates the reverse of the string using lambda expression. //ReverseStringLambda public class ReverseStringLambda { @FunctionalInterface interface StringReverser { String reverse(String str); } public static void main(String[] args) { StringReverser reverser = (str) -> new StringBuilder(str).reverse().toString(); String example = "Hello, World!"; String reversed = reverser.reverse(example); System.out.println("Original: " + example); System.out.println("Reversed: " + reversed); } } --------------------------------------------------------------------------------------------------------------------- 4. Write a java program to implement iterators on Array List and Linked List. //ArrayList import java.util.ArrayList; import java.util.Iterator; public class ArrayListIteratorExample { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); Iterator<String> iterator = fruits.iterator(); System.out.println("Using Iterator to traverse through the ArrayList:"); while (iterator.hasNext()) { String fruit = iterator.next(); System.out.println(fruit); } System.out.println("\nUsing for-each loop to traverse through the ArrayList:"); for (String fruit : fruits) { System.out.println(fruit); } iterator = fruits.iterator(); // Reset the iterator while (iterator.hasNext()) { String fruit = iterator.next(); if (fruit.startsWith("B")) { iterator.remove(); // Remove elements that start with "B" } } System.out.println("\nArrayList after removal of elements that start with 'B':"); for (String fruit : fruits) { System.out.println(fruit); } } } == //4.ALinkedList import java.util.LinkedList; import java.util.Iterator; public class LinkedListIteratorExample { public static void main(String[] args) { LinkedList<String> fruits = new LinkedList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); Iterator<String> iterator = fruits.iterator(); System.out.println("Using Iterator to traverse through the LinkedList:"); while (iterator.hasNext()) { String fruit = iterator.next(); System.out.println(fruit); } System.out.println("\nUsing for-each loop to traverse through the LinkedList:"); for (String fruit : fruits) { System.out.println(fruit); } iterator = fruits.iterator(); // Reset the iterator while (iterator.hasNext()) { String fruit = iterator.next(); if (fruit.startsWith("B")) { iterator.remove(); } } System.out.println("\nLinkedList after removal of elements that start with 'B':"); for (String fruit : fruits) { System.out.println(fruit); } } } --------------------------------------------------------------------------------------------------------------------- 5.a) Implement a Generic stack to deal with Integer, Double and String data using user defined arrays and linked lists. //5a)user-defined generic stack import java.util.Scanner; class Node<T> { T data; Node<T> next; public Node(T data) { this.data = data; this.next = null; } } class GenericStackArray<T> { private T[] stackArray; private int top; private int maxSize; @SuppressWarnings("unchecked") public GenericStackArray(int size) { this.maxSize = size; this.stackArray = (T[]) new Object[maxSize]; this.top = -1; } public void push(T item) { if (top < maxSize - 1) { stackArray[++top] = item; } else { System.out.println("Stack Overflow"); } } public T pop() { if (top >= 0) { return stackArray[top--]; } else { System.out.println("Stack Underflow"); return null; } } public boolean isEmpty() { return top == -1; } } class GenericStackLinkedList<T> { private Node<T> top; public GenericStackLinkedList() { this.top = null; } public void push(T item) { Node<T> newNode = new Node<>(item); newNode.next = top; top = newNode; } public T pop() { if (top == null) { System.out.println("Stack Underflow"); return null; } T data = top.data; top = top.next; return data; } public boolean isEmpty() { return top == null; } } public class GenericStackExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); GenericStackArray<Integer> intStackArray = new GenericStackArray<>(5); GenericStackLinkedList<Integer> intStackLinkedList = new GenericStackLinkedList<>(); System.out.println("Enter integers to push into the array stack (enter -1 to stop):"); int num; while (true) { num = scanner.nextInt(); if (num == -1) break; intStackArray.push(num); } System.out.println("Enter integers to push into the linked list stack (enter -1 to stop):"); while (true) { num = scanner.nextInt(); if (num == -1) break; intStackLinkedList.push(num); } System.out.println("Popping from array stack:"); while (!intStackArray.isEmpty()) { System.out.println(intStackArray.pop()); } System.out.println("Popping from linked list stack:"); while (!intStackLinkedList.isEmpty()) { System.out.println(intStackLinkedList.pop()); } } } ===== b) Implement a Generic queue to deal with Interger, Double and String data using user defined arrays and linked lists. //5b)User-defined Generic Queue import java.util.Scanner; class Node<T> { T data; Node<T> next; public Node(T data) { this.data = data; this.next = null; } } class GenericQueueArray<T> { private T[] queueArray; private int front, rear, size, capacity; @SuppressWarnings("unchecked") public GenericQueueArray(int capacity) { this.capacity = capacity; this.queueArray = (T[]) new Object[capacity]; this.front = 0; this.rear = capacity - 1; this.size = 0; } public void enqueue(T item) { if (isFull()) { System.out.println("Queue is full"); return; } rear = (rear + 1) % capacity; queueArray[rear] = item; size++; } public T dequeue() { if (isEmpty()) { System.out.println("Queue is empty"); return null; } T item = queueArray[front]; front = (front + 1) % capacity; size--; return item; } public boolean isEmpty() { return size == 0; } public boolean isFull() { return size == capacity; } } class GenericQueueLinkedList<T> { private Node<T> front, rear; public GenericQueueLinkedList() { this.front = this.rear = null; } public void enqueue(T item) { Node<T> newNode = new Node<>(item); if (isEmpty()) { front = rear = newNode; } else { rear.next = newNode; rear = newNode; } } public T dequeue() { if (isEmpty()) { System.out.println("Queue is empty"); return null; } T item = front.data; front = front.next; if (front == null) { rear = null; } return item; } public boolean isEmpty() { return front == null; } } public class GQueueExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); GenericQueueArray<Integer> intQueueArray = new GenericQueueArray<>(5); GenericQueueLinkedList<Integer> intQueueLinkedList = new GenericQueueLinkedList<>(); System.out.println("Enter integers to enqueue into the array queue (enter -1 to stop):"); int num; while (true) { num = scanner.nextInt(); if (num == -1) break; intQueueArray.enqueue(num); } System.out.println("Enter integers to enqueue into the linked list queue (enter -1 to stop):"); while (true) { num = scanner.nextInt(); if (num == -1) break; intQueueLinkedList.enqueue(num); } System.out.println("Dequeueing from array queue:"); while (!intQueueArray.isEmpty()) { System.out.println(intQueueArray.dequeue()); } System.out.println("Dequeueing from linked list queue:"); while (!intQueueLinkedList.isEmpty()) { System.out.println(intQueueLinkedList.dequeue()); } } } --------------------------------------------------------------------------------------------------------------------- 6. a) Write a java program to implement Generic stack using Array List Collection class. //6a)generic stack using arraylist class GStack<T> { private int maxSize; private T[] stackArray; private int top; public GStack(int size) { maxSize = size; stackArray = createGenericArray(maxSize); top = -1; } @SuppressWarnings("unchecked") private T[] createGenericArray(int size) { return (T[]) new Object[size]; } public void push(T element) { if (isFull()) { throw new StackOverflowError("Stack is full"); } stackArray[++top] = element; } public T pop() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stackArray[top--]; } public T peek() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stackArray[top]; } public boolean isEmpty() { return top == -1; } public boolean isFull() { return top == maxSize - 1; } } public class GStackArray { public static void main(String[] args) { GStack<Integer> intStack = new GStack<>(5); intStack.push(10); intStack.push(20); intStack.push(30); int poppedInt = intStack.pop(); System.out.println("Popped integer: " + poppedInt); int topInt = intStack.peek(); System.out.println("Top integer: " + topInt); boolean isIntStackEmpty = intStack.isEmpty(); System.out.println("Is stack of integers empty? " + isIntStackEmpty); boolean isIntStackFull = intStack.isFull(); System.out.println("Is stack of integers full? " + isIntStackFull); GStack<String> stringStack = new GStack<>(3); stringStack.push("Hello"); stringStack.push("World"); String poppedString = stringStack.pop(); System.out.println("Popped string: " + poppedString); String topString = stringStack.peek(); System.out.println("Top string: " + topString); boolean isStringStackEmpty = stringStack.isEmpty(); System.out.println("Is stack of strings empty? " + isStringStackEmpty); boolean isStringStackFull = stringStack.isFull(); System.out.println("Is stack of strings full? " + isStringStackFull); } } --------------------------------------------------------------------------------------------------------------------- 6.b) Write a java program to implement Generic stack using LinkedList Collection class. //6b)generic stack using linked list import java.util.LinkedList; class GStack<T> { private LinkedList<T> stack; public GStack() { stack = new LinkedList<>(); } public void push(T element) { stack.addLast(element); } public T pop() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stack.removeLast(); } public T peek() { if (isEmpty()) { throw new IllegalStateException("Stack is empty"); } return stack.getLast(); } public boolean isEmpty() { return stack.isEmpty(); } public int size() { return stack.size(); } } public class GStackLinkedList { public static void main(String[] args) { GStack<Integer> intStack = new GStack<>(); intStack.push(10); intStack.push(20); intStack.push(30); int poppedInt = intStack.pop(); System.out.println("Popped integer: " + poppedInt); int topInt = intStack.peek(); System.out.println("Top integer: " + topInt); boolean isIntStackEmpty = intStack.isEmpty(); System.out.println("Is stack of integers empty? " + isIntStackEmpty); GStack<String> stringStack = new GStack<>(); stringStack.push("Hello"); stringStack.push("World"); String poppedString = stringStack.pop(); System.out.println("Popped string: " + poppedString); String topString = stringStack.peek(); System.out.println("Top string: " + topString); boolean isStringStackEmpty = stringStack.isEmpty(); System.out.println("Is stack of strings empty? " + isStringStackEmpty); } } 7.a) Write a Java program to implement Generic queue using ArrayList Collection class. //7a)generic queue using arraylist import java.util.ArrayList; class GenericQueue<T> { private ArrayList<T> queue; public GenericQueue() { queue = new ArrayList<>(); } public void enqueue(T element) { queue.add(element); } public T dequeue() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return queue.remove(0); } public T peek() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return queue.get(0); } public boolean isEmpty() { return queue.isEmpty(); } public int size() { return queue.size(); } } public class GenericQueueExample { public static void main(String[] args) { GenericQueue<Integer> intQueue = new GenericQueue<>(); intQueue.enqueue(10); intQueue.enqueue(20); intQueue.enqueue(30); System.out.println("Dequeued element: " + intQueue.dequeue()); System.out.println("Peeked element: " + intQueue.peek()); System.out.println("Queue size: " + intQueue.size()); GenericQueue<String> stringQueue = new GenericQueue<>(); stringQueue.enqueue("Hello"); stringQueue.enqueue("World"); System.out.println("\nDequeued element: " + stringQueue.dequeue()); System.out.println("Peeked element: " + stringQueue.peek()); System.out.println("Queue size: " + stringQueue.size()); } } 7.b) Write a java program to implement Generic queue using LinkedList Collection class. //7b)generic queue using arraylist import java.util.LinkedList; class GenericQueue<T> { private LinkedList<T> q; public GenericQueue() { q = new LinkedList<>(); } public void enqueue(T element) { q.add(element); } public T dequeue() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return q.remove(0); } public T peek() { if (isEmpty()) { throw new IllegalStateException("Queue is empty"); } return q.get(0); } public boolean isEmpty() { return q.isEmpty(); } public int size() { return q.size(); } } public class GenericQueueLLExample { public static void main(String[] args) { GenericQueue<Integer> intQueue = new GenericQueue<>(); intQueue.enqueue(10); intQueue.enqueue(20); intQueue.enqueue(30); System.out.println("Dequeued element: " + intQueue.dequeue()); System.out.println("Peeked element: " + intQueue.peek()); System.out.println("Queue size: " + intQueue.size()); GenericQueue<String> stringQueue = new GenericQueue<>(); stringQueue.enqueue("Hello"); stringQueue.enqueue("World"); System.out.println("\nDequeued element: " + stringQueue.dequeue()); System.out.println("Peeked element: " + stringQueue.peek()); System.out.println("Queue size: " + stringQueue.size()); } } --------------------------------------------------------------------------------------------------------------------- 8) Write a java program to demonstrate the use of the following Collection classes. a. HashSet //8a)HashSet import java.util.*; import java.util.HashSet; import java.util.Iterator; class Contact { private String name; private String email; public Contact(String name, String email) { this.name = name; this.email = email; } public String getName() { return name; } public String getEmail() { return email; } @Override public String toString() { return "Contact{" + "name='" + name + '\'' + ", email='" + email + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Contact contact = (Contact) o; return name.equals(contact.name) && email.equals(contact.email); } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + email.hashCode(); return result; } } public class HashSetContactDemo { public static void main(String[] args) { HashSet<Contact> contactSet = new HashSet<>(); contactSet.add(new Contact("John", "john@example.com")); contactSet.add(new Contact("Jane", "jane@example.com")); contactSet.add(new Contact("Alice", "alice@example.com")); System.out.println("HashSet of Contacts:"); for (Contact contact : contactSet) { System.out.println(contact); } // Demonstrate contains method Contact searchContact = new Contact("John", "john@example.com"); System.out.println("Contains 'John'? " + contactSet.contains(searchContact)); // Demonstrate isEmpty method System.out.println("Is the HashSet empty? " + contactSet.isEmpty()); System.out.println("Size of the HashSet: " + contactSet.size()); // Demonstrate remove method contactSet.remove(new Contact("Jane", "jane@example.com")); System.out.println("HashSet after removing 'Jane': " + contactSet); // Adding contacts again for further demonstrations contactSet.add(new Contact("Jane", "jane@example.com")); // Demonstrate iteration using iterator System.out.println("Iteration using Iterator:"); Iterator<Contact> iterator = contactSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } // Demonstrate toArray method Object[] array = contactSet.toArray(); System.out.print("HashSet as Array: "); for (Object element : array) { System.out.print(element + " "); } System.out.println(); // Demonstrate hashCode method System.out.println("Hash code of the HashSet: " + contactSet.hashCode()); } } ======= b. Linked List //8b)LinkedHashSet import java.util.LinkedHashSet; import java.util.Iterator; public class LinkedHashSetDemo { public static void main(String[] args) { LinkedHashSet<String> lhs= new LinkedHashSet<>(); lhs.add("Apple"); lhs.add("Banana"); lhs.add("Orange"); lhs.add("Grapes"); lhs.add("Watermelon"); System.out.println("LinkedHashSet: " + lhs); System.out.println("Contains 'Banana'? " + lhs.contains("Banana")); System.out.println("Is the LinkedHashSet empty? " + lhs.isEmpty()); System.out.println("Size of the LinkedHashSet: " + lhs.size()); lhs.remove("Orange"); System.out.println("LinkedHashSet after removing 'Orange': " + lhs); lhs.clear(); System.out.println("LinkedHashSet after clearing: " + lhs); lhs.add("Apple"); lhs.add("Banana"); lhs.add("Orange"); System.out.println("Iteration using Iterator:"); Iterator<String> iterator = lhs.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } Object[] array = lhs.toArray(); System.out.print("LinkedHashSet as Array: "); for (Object element : array) { System.out.print(element + " "); } System.out.println(); System.out.println("Hash code of the LinkedHashSet: " + lhs.hashCode()); } } === c. TreeSet //8c)TreeSet import java.util.TreeSet; import java.util.Iterator; import java.util.TreeSet; import java.util.Iterator; class Employee2 implements Comparable<Employee2> { private String name; private int id; public Employee2(String name, int id) { this.name = name; this.id = id; } public String getName() { return name; } public int getId() { return id; } @Override public int compareTo(Employee2 other) { return Integer.compare(this.id, other.id); } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + ", id=" + id + '}'; } } public class TreeSetEmployeeDemo { public static void main(String[] args) { TreeSet<Employee2> treeSet = new TreeSet<>(); treeSet.add(new Employee2("John", 101)); treeSet.add(new Employee2("Jane", 102)); treeSet.add(new Employee2("Alice", 103)); System.out.println("TreeSet of Employees:"); for (Employee2 employee : treeSet) { System.out.println(employee); } Employee2 searchEmployee = new Employee2("John", 101); System.out.println("Contains 'John'? " + treeSet.contains(searchEmployee)); System.out.println("Is the TreeSet empty? " + treeSet.isEmpty()); System.out.println("Size of the TreeSet: " + treeSet.size()); treeSet.remove(new Employee2("Jane", 102)); System.out.println("TreeSet after removing 'Jane': " + treeSet); treeSet.clear(); System.out.println("TreeSet after clearing: " + treeSet); treeSet.add(new Employee2("John", 101)); treeSet.add(new Employee2("Jane", 102)); System.out.println("Iteration using Iterator:"); Iterator<Employee2> iterator = treeSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } Object[] array = treeSet.toArray(); System.out.print("TreeSet as Array: "); for (Object element : array) { System.out.print(element + " "); } System.out.println(); System.out.println("Hash code of the TreeSet: " + treeSet.hashCode()); } }--------------------------------------------------------------------------------------------------------------------- 9. Write a java program to create a class called Person with income,age and name as its members. Read set A of persons from a suer and compute the following sets: i) Set B of persons whose age > 60 ii) Set C of persons whose income < 10000 and iii) B and C 9)Person program import java.util.ArrayList; import java.util.List; import java.util.Scanner; class Person { private String name; private int age; private double income; public Person(String name, int age, double income) { this.name = name; this.age = age; this.income = income; } public String getName() { return name; } public int getAge() { return age; } public double getIncome() { return income; } } public class PersonExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); List<Person> setA = new ArrayList<>(); System.out.print("Enter the number of persons: "); int n = scanner.nextInt(); scanner.nextLine(); // consume newline character for (int i = 0; i < n; i++) { System.out.println("Enter details for person " + (i + 1) + ":"); System.out.print("Name: "); String name = scanner.nextLine(); System.out.print("Age: "); int age = scanner.nextInt(); System.out.print("Income: "); double income = scanner.nextDouble(); scanner.nextLine(); // consume newline character Person person = new Person(name, age, income); setA.add(person); } List<Person> setB = new ArrayList<>(); List<Person> setC = new ArrayList<>(); List<Person> setBC = new ArrayList<>(); for (Person person : setA) { if (person.getAge() > 60) { setB.add(person); } if (person.getIncome() < 10000) { setC.add(person); } if (person.getAge() > 60 && person.getIncome() < 10000) { setBC.add(person); } } System.out.println("Set A: "); for (Person person : setA) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } System.out.println("\nSet B (age > 60): "); for (Person person : setB) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } System.out.println("\nSet C (income < 10000): "); for (Person person : setC) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } System.out.println("\nSet B and C (age > 60 and income < 10000): "); for (Person person : setBC) { System.out.println("Name: " + person.getName() + ", Age: " + person.getAge() + ", Income: " + person.getIncome()); } } } --------------------------------------------------------------------------------------------------------------------- 10. Write a java program to demonstrate the use of the following Collection classes. a. HashMap //10a)HashMap import java.util.HashMap; import java.util.Map; public class HashMapExample{ public static void main(String[] args) { Map<String, Integer> ageMap = new HashMap<>(); ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); ageMap.put("Eve", 28); System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } ageMap.remove("Eve"); System.out.println("Map after removing Eve: " + ageMap); System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } } ===== b.LinkedHashMap //10b)LinkedHashMap import java.util.LinkedHashMap; import java.util.Map; public class LinkedHashMapExample{ public static void main(String[] args) { Map<String, Integer> ageMap = new LinkedHashMap<>(); ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); ageMap.put("Eve", 28); System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } ageMap.remove("Eve"); System.out.println("Map after removing Eve: " + ageMap); System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } } ==== c.TreeMap //10c)TreeMap import java.util.TreeMap; import java.util.Map; public class TreeMapExample{ public static void main(String[] args) { Map<String, Integer> ageMap = new TreeMap<>(); ageMap.put("John", 30); ageMap.put("Alice", 25); ageMap.put("Bob", 35); ageMap.put("Eve", 28); System.out.println("Age of John: " + ageMap.get("John")); System.out.println("Age of Alice: " + ageMap.get("Alice")); ageMap.put("John", 32); System.out.println("Updated age of John: " + ageMap.get("John")); String name = "Bob"; if (ageMap.containsKey(name)) { System.out.println(name + " exists in the map."); } else { System.out.println(name + " does not exist in the map."); } ageMap.remove("Eve"); System.out.println("Map after removing Eve: " + ageMap); System.out.println("Iterating over map entries:"); for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } ageMap.clear(); System.out.println("Map after clearing: " + ageMap); } } --------------------------------------------------------------------------------------------------------------------- 11. Create a class Product(id,name,price,type,rating) and perform the following operations using stream: i) Find all the products having rating between 4 and 5. ii) Find first n products having price > 10000. iii) Find the number of products under each type(map containing type and count) iv) Find average rating of products woth type = “Electronics”. //11)Product stream import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; class Product { private int id; private String name; private double price; private String type; private double rating; public Product(int id, String name, double price, String type, double rating) { this.id = id; this.name = name; this.price = price; this.type = type; this.rating = rating; } public double getRating() { return rating; } public double getPrice() { return price; } public String getType() { return type; } @Override public String toString() { return "Product{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + ", type='" + type + '\'' + ", rating=" + rating + '}'; } } public class ProductStreamExample { public static void main(String[] args) { List<Product> products = Arrays.asList( new Product(1, "Laptop", 1500.0, "Electronics", 4.5), new Product(2, "Smartphone", 800.0, "Electronics", 4.2), new Product(3, "Watch", 300.0, "Fashion", 3.8), new Product(4, "Headphones", 100.0, "Electronics", 4.8), new Product(5, "Shoes", 50.0, "Fashion", 3.5), new Product(6, "Camera", 2000.0, "Electronics", 4.7) ); // i) Find all the products having rating between 4 and 5 List<Product> productsRatingBetween4And5 = products.stream() .filter(p -> p.getRating() >= 4 && p.getRating() <= 5) .collect(Collectors.toList()); System.out.println("Products with rating between 4 and 5: " + productsRatingBetween4And5); System.out.println(); // ii) Find first n products having price > 1000 int n = 2; List<Product> firstNProductsPriceGreaterThan1000 = products.stream() .filter(p -> p.getPrice() > 1000) .limit(n) .collect(Collectors.toList()); System.out.println("First " + n + " products with price > 1000: " + firstNProductsPriceGreaterThan1000); System.out.println(); // iii) Find the number of products under each type (map containing type and count) Map<String, Long> productCountByType = products.stream() .collect(Collectors.groupingBy(Product::getType, Collectors.counting())); System.out.println("Number of products under each type: " + productCountByType); System.out.println(); // iv) Find average rating of products with type = "Electronics" double averageRatingElectronics = products.stream() .filter(p -> p.getType().equals("Electronics")) .mapToDouble(Product::getRating) .average() .orElse(0.0); System.out.println("Average rating of products with type 'Electronics': " + averageRatingElectronics); } } -------------------------------------------------------------------------------------------------------------------12. Write a Java program to implement Sorted Chain. //12)Sorted Chain class Node<T extends Comparable<T>> { T data; Node<T> next; public Node(T data) { this.data = data; this.next = null; } } public class SortedChain<T extends Comparable<T>> { private Node<T> head; public void insert(T data) { Node<T> newNode = new Node<>(data); if (head == null || head.data.compareTo(data) >= 0) { newNode.next = head; head = newNode; } else { Node<T> current = head; while (current.next != null && current.next.data.compareTo(data) < 0) { current = current.next; } newNode.next = current.next; current.next = newNode; } } public void display() { Node<T> current = head; while (current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } public static void main(String[] args) { SortedChain<Integer> sortedChain = new SortedChain<>(); sortedChain.insert(5); sortedChain.insert(3); sortedChain.insert(7); sortedChain.insert(1); sortedChain.insert(9); System.out.println("Sorted Chain:"); sortedChain.display(); } } --------------------------------------------------------------------------------------------------------------------- 13. Write a java program to implement Separate Chaining //13)SeparateChaining import java.util.LinkedList; class KeyValuePair<K, V> { private K key; private V value; public KeyValuePair(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } } class SeparateChaining<K, V> { private LinkedList<KeyValuePair<K, V>>[] table; private int capacity; @SuppressWarnings("unchecked") public SeparateChaining(int capacity) { this.capacity = capacity; this.table = new LinkedList[capacity]; for (int i = 0; i < capacity; i++) { table[i] = new LinkedList<>(); } } private int hash(K key) { return Math.abs(key.hashCode() % capacity); } public void put(K key, V value) { int index = hash(key); LinkedList<KeyValuePair<K, V>> list = table[index]; for (KeyValuePair<K, V> pair : list) { if (pair.getKey().equals(key)) { pair = new KeyValuePair<>(key, value); return; } } list.add(new KeyValuePair<>(key, value)); } public V get(K key) { int index = hash(key); LinkedList<KeyValuePair<K, V>> list = table[index]; for (KeyValuePair<K, V> pair : list) { if (pair.getKey().equals(key)) { return pair.getValue(); } } return null; } public void remove(K key) { int index = hash(key); LinkedList<KeyValuePair<K, V>> list = table[index]; for (KeyValuePair<K, V> pair : list) { if (pair.getKey().equals(key)) { list.remove(pair); return; } } } } public class SeparateChainingExample { public static void main(String[] args) { SeparateChaining<String, Integer> map = new SeparateChaining<>(5); map.put("John", 25); map.put("Alice", 30); map.put("Bob", 35); System.out.println("Alice's age: " + map.get("Alice")); System.out.println("Bob's age: " + map.get("Bob")); map.remove("Alice"); System.out.println("Alice's age after removal: " + map.get("Alice")); } } --------------------------------------------------------------------------------------------------------------------- 14. Write a java program to implement Linear Probing. //14)LinearProbing public class LinearProbingHashTable { private String[] keys; private String[] values; private int size; private int capacity; public LinearProbingHashTable(int capacity) { this.capacity = capacity; this.keys = new String[capacity]; this.values = new String[capacity]; this.size = 0; } private int hash(String key) { return key.length() % capacity; } public void put(String key, String value) { if (key == null || value == null) { throw new IllegalArgumentException("Key or value cannot be null."); } int index = hash(key); while (keys[index] != null) { if (keys[index].equals(key)) { values[index] = value; return; } index = (index + 1) % capacity; } keys[index] = key; values[index] = value; size++; } public String get(String key) { int index = hash(key); while (keys[index] != null) { if (keys[index].equals(key)) { return values[index]; } index = (index + 1) % capacity; } return null; } public void display() { for (int i = 0; i < capacity; i++) { if (keys[i] != null) { System.out.println("Key: " + keys[i] + ", Value: " + values[i]); } } } public static void main(String[] args) { LinearProbingHashTable hashTable = new LinearProbingHashTable(10); hashTable.put("John", "Doe"); hashTable.put("Alice", "Smith"); hashTable.put("Bob", "Johnson"); hashTable.put("Charlie", "Brown"); hashTable.display(); System.out.println("Value associated with 'John': " + hashTable.get("John")); System.out.println("Value associated with 'Alice': " + hashTable.get("Alice")); System.out.println("Value associated with 'Bob': " + hashTable.get("Bob")); System.out.println("Value associated with 'Charlie': " + hashTable.get("Charlie")); System.out.println("Value associated with 'Dave': " + hashTable.get("Dave")); // Not found } } 15. Implement BST using Collection API, and use recursive procedures to implement inOrder, preorder and postOrder traversals. //15)BinarySearchTree import java.util.LinkedList; class TreeNode<T extends Comparable<T>> { T data; TreeNode<T> left, right; public TreeNode(T data) { this.data = data; this.left = null; this.right = null; } } public class BinarySearchTree<T extends Comparable<T>> { private TreeNode<T> root; public BinarySearchTree() { this.root = null; } public void insert(T data) { root = insertRec(root, data); } private TreeNode<T> insertRec(TreeNode<T> root, T data) { if (root == null) { root = new TreeNode<>(data); return root; } if (data.compareTo(root.data) < 0) { root.left = insertRec(root.left, data); } else if (data.compareTo(root.data) > 0) { root.right = insertRec(root.right, data); } return root; } public void inorderTraversal() { inorderTraversalRec(root); } private void inorderTraversalRec(TreeNode<T> root) { if (root != null) { inorderTraversalRec(root.left); System.out.print(root.data + " "); inorderTraversalRec(root.right); } } public void preorderTraversal() { preorderTraversalRec(root); } private void preorderTraversalRec(TreeNode<T> root) { if (root != null) { System.out.print(root.data + " "); preorderTraversalRec(root.left); preorderTraversalRec(root.right); } } public void postorderTraversal() { postorderTraversalRec(root); } private void postorderTraversalRec(TreeNode<T> root) { if (root != null) { postorderTraversalRec(root.left); postorderTraversalRec(root.right); System.out.print(root.data + " "); } } public void delete(T data) { root = deleteRec(root, data); } private TreeNode<T> deleteRec(TreeNode<T> root, T data) { if (root == null) return root; if (data.compareTo(root.data) < 0) { root.left = deleteRec(root.left, data); } else if (data.compareTo(root.data) > 0) { root.right = deleteRec(root.right, data); } else { if (root.left == null) return root.right; else if (root.right == null) return root.left; root.data = minValue(root.right); root.right = deleteRec(root.right, root.data); } return root; } private T minValue(TreeNode<T> root) { T minv = root.data; while (root.left != null) { minv = root.left.data; root = root.left; } return minv; } public static void main(String[] args) { BinarySearchTree<Integer> bst = new BinarySearchTree<>(); bst.insert(50); bst.insert(30); bst.insert(20); bst.insert(40); bst.insert(70); bst.insert(60); bst.insert(80); System.out.println("Inorder traversal:"); bst.inorderTraversal(); System.out.println("\nPreorder traversal:"); bst.preorderTraversal(); System.out.println("\nPostorder traversal:"); bst.postorderTraversal(); System.out.println("\nDeleting 20:"); bst.delete(20); System.out.println("Inorder traversal after deletion:"); bst.inorderTraversal(); } } 16. Implement AVL tree using Collection API. //16)AVL TRee import java.util.Comparator; class AVLNode<T extends Comparable<T>> { T data; AVLNode<T> left, right; int height; public AVLNode(T data) { this.data = data; this.left = null; this.right = null; this.height = 1; } } public class AVLTree<T extends Comparable<T>> { private AVLNode<T> root; public AVLTree() { this.root = null; } private int height(AVLNode<T> node) { if (node == null) return 0; return node.height; } private int getBalance(AVLNode<T> node) { if (node == null) return 0; return height(node.left) - height(node.right); } public AVLNode<T> insert(AVLNode<T> node, T data) { if (node == null) return new AVLNode<>(data); if (data.compareTo(node.data) < 0) { node.left = insert(node.left, data); } else if (data.compareTo(node.data) > 0) { node.right = insert(node.right, data); } else { return node; // Duplicate keys not allowed } // Update height of this ancestor node node.height = 1 + Math.max(height(node.left), height(node.right)); // Get the balance factor and perform rotation if needed int balance = getBalance(node); // Left Left Case if (balance > 1 && data.compareTo(node.left.data) < 0) { return rightRotate(node); } // Right Right Case if (balance < -1 && data.compareTo(node.right.data) > 0) { return leftRotate(node); } // Left Right Case if (balance > 1 && data.compareTo(node.left.data) > 0) { node.left = leftRotate(node.left); return rightRotate(node); } // Right Left Case if (balance < -1 && data.compareTo(node.right.data) < 0) { node.right = rightRotate(node.right); return leftRotate(node); } return node; } private AVLNode<T> rightRotate(AVLNode<T> y) { AVLNode<T> x = y.left; AVLNode<T> T2 = x.right; // Perform rotation x.right = y; y.left = T2; // Update heights y.height = Math.max(height(y.left), height(y.right)) + 1; x.height = Math.max(height(x.left), height(x.right)) + 1; return x; } private AVLNode<T> leftRotate(AVLNode<T> x) { AVLNode<T> y = x.right; AVLNode<T> T2 = y.left; // Perform rotation y.left = x; x.right = T2; // Update heights x.height = Math.max(height(x.left), height(x.right)) + 1; y.height = Math.max(height(y.left), height(y.right)) + 1; return y; } public void insert(T data) { root = insert(root, data); } public void inorderTraversal() { inorderTraversal(root); System.out.println(); } private void inorderTraversal(AVLNode<T> node) { if (node != null) { inorderTraversal(node.left); System.out.print(node.data + " "); inorderTraversal(node.right); } } public static void main(String[] args) { AVLTree<Integer> avlTree = new AVLTree<>(); avlTree.insert(10); avlTree.insert(20); avlTree.insert(30); avlTree.insert(40); avlTree.insert(50); avlTree.insert(25); System.out.println("Inorder traversal:"); avlTree.inorderTraversal(); } }
Comments