0% found this document useful (0 votes)
4 views14 pages

Java2 Assginment

The document contains Java code examples demonstrating various data structure operations, including creating and manipulating ArrayLists, removing duplicates using HashSets, finding minimum and maximum values in LinkedLists, counting character frequencies with HashMaps, sorting custom objects, merging sets, using TreeMaps for student grades, implementing a stack with LinkedLists, creating an LRU cache with LinkedHashMap, and solving a producer-consumer problem with BlockingQueue. Each example is self-contained and illustrates specific functionalities of Java collections. The code snippets are organized under different classes and methods, showcasing practical applications of data structures in Java.

Uploaded by

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

Java2 Assginment

The document contains Java code examples demonstrating various data structure operations, including creating and manipulating ArrayLists, removing duplicates using HashSets, finding minimum and maximum values in LinkedLists, counting character frequencies with HashMaps, sorting custom objects, merging sets, using TreeMaps for student grades, implementing a stack with LinkedLists, creating an LRU cache with LinkedHashMap, and solving a producer-consumer problem with BlockingQueue. Each example is self-contained and illustrates specific functionalities of Java collections. The code snippets are organized under different classes and methods, showcasing practical applications of data structures in Java.

Uploaded by

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

1.

List all elements of an ArrayList Create an ArrayList of integers, add 5 elements, and print
all elements using a simple for loop.

package Assignment04;

import java.util.ArrayList;

import java.util.Scanner;

public class ArrayListExample {

public static void main(String[] args) {

ArrayList<Integer> numbers = new ArrayList<>();


Scanner scanner = new Scanner(System.in);

System.out.println("Enter 5 integers:");

for (int i = 0; i < 5; i++) {

System.out.print("Enter number " + (i + 1) + ": ");

int num = scanner.nextInt();


numbers.add(num);

System.out.println("Elements in the ArrayList:");

for (int i = 0; i < numbers.size(); i++) {

System.out.println(numbers.get(i));

scanner.close();

Output:
2. Remove duplicates from a List
Given a List of strings with duplicates, use a HashSet to remove duplicates and print the
unique elements.

package Assignment04;

import java.util.Arrays;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

public class RemoveDuplicates {

public static void main(String[] args) {

List<String> names = Arrays.asList("Ali", "Baba", "Ali", "Chalees", "Baba");

Set<String> uniqueNames = new HashSet<>(names);


System.out.println(uniqueNames);

}
}

Output:

3. Find maximum and minimum in a LinkedList


Add 10 random numbers to a LinkedList and find the maximum and minimum values
without sorting.

package Assignment04;

import java.util.*;

public class LinkedListMinMax {

public static void main(String[] args) {

LinkedList<Integer> numbers = new LinkedList<>();

Random rand = new Random();

for (int i = 0; i < 10; i++) {


numbers.add(rand.nextInt(100));

System.out.println("List: " + numbers);

System.out.println("Max: " + Collections.max(numbers));

System.out.println("Min: " + Collections.min(numbers));

Output:

4. Count frequency of characters using HashMap

Given a string, count the frequency of each character using a HashMap and print the
results.

package Assignment04;

import java.util.*;
public class CharFrequency {

public static void main(String[] args) {

String input = "programming";

Map<Character, Integer> freq = new HashMap<>();

for (char ch : input.toCharArray()) {

freq.put(ch, freq.getOrDefault(ch, 0) + 1);

System.out.println(freq);
}

Output:
5. Sort a list of custom objects using ComparableCreate a Student class with id, name,
and age. Use an ArrayList of Student objects and sort them by age using the
Comparable interface.

package Assignment04;
import java.util.*;

class Student implements Comparable<Student> {


int id;
String name;
int age;
Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}

public int compareTo(Student s) {


return this.age - s.age;
}
public String toString() {
return id + " " + name + " " + age;
}
}

public class SortStudents {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student(1, "Poonam", 22));
students.add(new Student(2, "Divya", 20));
students.add(new Student(3, "Alizeh", 23));

Collections.sort(students);
for (Student s : students) {
System.out.println(s);
}
}
}
Output:

6. Merge two sets and find intersection


Create two HashSet<Integer> with some common and some distinct elements. Write
methods to merge both sets and find their intersection.
package Assignment04;

import java.util.*;

public class SetMergeIntersection {


public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> set2 = new HashSet<>(Arrays.asList(4, 5, 6, 7, 8));

Set<Integer> merged = new HashSet<>(set1);


merged.addAll(set2);
System.out.println("Merged: " + merged);

Set<Integer> intersection = new HashSet<>(set1);


intersection.retainAll(set2);
System.out.println("Intersection: " + intersection);
}
}
Output:

7. Use TreeMap to store and display students by grade


Create a TreeMap<Integer, String> where key is the student's grade and value is student
name. Insert data and display in ascending order of grade.
package Assignment04;

import java.util.*;

public class TreeMapExample {


public static void main(String[] args) {
TreeMap<Integer, String> students = new TreeMap<>();
students.put(90, "Simmi");
students.put(85, "Kavya");
students.put(96, "Alex");

for (Map.Entry<Integer, String> entry : students.entrySet()) {


System.out.println("Grade: " + entry.getKey() + ", Name: " + entry.getValue());
}
}
}
Output:

8. Implement a simple stack using LinkedList Use LinkedList to implement stack operations:
push, pop,peek. Test with integer values.
package Assignment04;

import java.util.*;

public class StackUsingLinkedList {


public static void main(String[] args) {
LinkedList<Integer> stack = new LinkedList<>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(60);
System.out.println("Popped: " + stack.pop());
System.out.println("Peek: " + stack.peek());
}
}
Output:

9. Implement LRU Cache using LinkedHashMap Create a class LRUCache with a fixed
capacity. Use LinkedHashMap to store key-value pairs and implement get put methods.
When cache exceeds capacity, remove least recently used entry
package Assignment04;

import java.util.*;

class LRUCache<K, V> extends LinkedHashMap<K, V> {


private int capacity;

public LRUCache(int capacity) {


super(capacity, 0.75f, true);
this.capacity = capacity;
}

protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {


return size() > capacity;
}
}

public class LRUExample {


public static void main(String[] args) {
LRUCache<Integer, String> cache = new LRUCache<>(3);
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
System.out.println(cache);
cache.get(1);
cache.put(4, "D");
System.out.println(cache);
}
}
Output:

10. Multi-threaded producer-consumer problem using BinckingQueue:

Create a producer thread that adds elements to a LinkedBlockingQueue and a


consumer thread that consumes elements. Implement proper synchronization and
thread-safe collection use

package Assignment04;

import java.util.concurrent.*;
class Producer implements Runnable {

private BlockingQueue<Integer> queue;

public Producer(BlockingQueue<Integer> queue) {

this.queue = queue;

public void run() {

try {
for (int count = 0; count < 7; count++) {

System.out.println("Producing: " + count);


queue.put(count);

Thread.sleep(500);

} catch (InterruptedException e) {

Thread.currentThread().interrupt();
}

}
}

class Consumer implements Runnable {

private BlockingQueue<Integer> queue;

public Consumer(BlockingQueue<Integer> queue) {

this.queue = queue;

public void run() {

try {
for (int i = 0; i < 7; i++) {

Integer value = queue.take();

System.out.println("Consumed: " + value);

Thread.sleep(1000);

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

}
}

public class ProducerConsumer {

public static void main(String[] args) {

BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(5);

Thread producerThread = new Thread(new Producer(queue));


Thread consumerThread = new Thread(new Consumer(queue));

producerThread.start();

consumerThread.start();

try {

producerThread.join();

consumerThread.join();

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

System.out.println("Both Producer and Consumer have completed processing 7 items.");

}
}

Output:

You might also like