0% found this document useful (0 votes)
29 views20 pages

Collection

The document contains multiple Java programming assignments focused on data structures such as ArrayList, LinkedList, Vector, HashSet, TreeSet, and HashMap. Each assignment includes code examples for creating and manipulating these data structures, such as managing employee records, storing country names, and iterating through collections. The document serves as a comprehensive guide for practicing Java collection frameworks and implementing various functionalities.

Uploaded by

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

Collection

The document contains multiple Java programming assignments focused on data structures such as ArrayList, LinkedList, Vector, HashSet, TreeSet, and HashMap. Each assignment includes code examples for creating and manipulating these data structures, such as managing employee records, storing country names, and iterating through collections. The document serves as a comprehensive guide for practicing Java collection frameworks and implementing various functionalities.

Uploaded by

jahnavis.mel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

List

1.write a java program to create an array list,add all the months of a year nad
print the same
import java.util.ArrayList;

public class MonthsArrayList {


public static void main(String[] args) {

ArrayList<String> months = new ArrayList<>();

months.add("January");
months.add("February");
months.add("March");
months.add("April");
months.add("May");
months.add("June");
months.add("July");
months.add("August");
months.add("September");
months.add("October");
months.add("November");
months.add("December");

System.out.println("Months of the Year:");


for (String month : months) {
System.out.println(month);
}
}
}

2. 1) Create an application for employee management with the following classes:

a) Create an Employee class with following attributes and behaviors :


i) int empId
ii)String empName
iii)String email
iv)String gender
v)float salary
vi) void GetEmployeeDetails() -> prints employee details

b) Create one more class EmployeeDB with the following attributes and behaviors.
(i) ArrayList list;
ii) boolean addEmployee(Employee e) -> adds the employee object to the
collection
iii) boolean deleteEmployee(int empId) ->delete the employee object from the
collection with the given empid
iv) String showPaySlip(int empId) -> returns the payslip of the employee with
the given empId

Provide implementation for all the methods and test your program.

import java.util.ArrayList;

// Employee class
class Employee {
int empId;
String empName;
String email;
String gender;
float salary;

// Constructor
public Employee(int empId, String empName, String email, String gender, float
salary) {
this.empId = empId;
this.empName = empName;
this.email = email;
this.gender = gender;
this.salary = salary;
}

// Method to display employee details


public void GetEmployeeDetails() {
System.out.println("Employee ID: " + empId);
System.out.println("Name : " + empName);
System.out.println("Email : " + email);
System.out.println("Gender : " + gender);
System.out.println("Salary : " + salary);
System.out.println("---------------------------");
}
}

// EmployeeDB class
class EmployeeDB {
ArrayList<Employee> list = new ArrayList<>();

// Add employee (no return type)


public void addEmployee(Employee e) {
if (e != null) {
list.add(e);
}
}

// Delete employee by empId


public boolean deleteEmployee(int empId) {
for (Employee e : list) {
if (e.empId == empId) {
list.remove(e);
return true;
}
}
return false; // not found
}

// Show payslip of employee


public String showPaySlip(int empId) {
for (Employee e : list) {
if (e.empId == empId) {
return "Payslip for employee ID " + empId + ": Salary = " +
e.salary;
}
}
return "Employee with ID " + empId + " not found!";
}
}
// Main class to test
public class EmployeeManagementApp {
public static void main(String[] args) {
EmployeeDB db = new EmployeeDB();

// Create employees
Employee e1 = new Employee(101, "Alice", "alice@example.com", "Female",
50000f);
Employee e2 = new Employee(102, "Bob", "bob@example.com", "Male", 60000f);
Employee e3 = new Employee(103, "Charlie", "charlie@example.com", "Male",
55000f);

// Add employees (no boolean check needed)


db.addEmployee(e1);
db.addEmployee(e2);
db.addEmployee(e3);

// Display all employee details


System.out.println("---- Employee Details ----");
for (Employee e : db.list) {
e.GetEmployeeDetails();
}

// Show payslip
System.out.println(db.showPaySlip(102));

// Delete an employee
if (db.deleteEmployee(101)) {
System.out.println("Employee with ID 101 deleted successfully.");
} else {
System.out.println("Employee not found.");
}

// Display remaining employees


System.out.println("---- Remaining Employees ----");
for (Employee e : db.list) {
e.GetEmployeeDetails();
}
}
}

3. Create an ArrayList that can store only Strings. Create a printAll method that
will print all the elements of the ArrayList using an Iterator.
import java.util.ArrayList;
import java.util.Iterator;

public class StringArrayListDemo {

public static void printAll(ArrayList<String> list) {


Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}

public static void main(String[] args) {


ArrayList<String> stringList = new ArrayList<>();

stringList.add("Apple");
stringList.add("Banana");
stringList.add("Cherry");
stringList.add("Mango");

System.out.println("Elements in ArrayList:");
printAll(stringList);
}
}

4.Create an ArrayList that can store only numbers like int, float, double, etc, but
not any other data type.
import java.util.ArrayList;

public class NumberArrayListDemo {


public static void main(String[] args) {

ArrayList<Number> numberList = new ArrayList<>();


numberList.add(10);
numberList.add(15.75f);
numberList.add(20.99);
numberList.add(123456789L);
System.out.println("Numbers in the list:");
for (Number num : numberList) {
System.out.println(num);
}

}
}

5. implement assignment 1 using linked list


import java.util.LinkedList;

public class MonthsLinkedList {


public static void main(String[] args) {

// Create a LinkedList to store months


LinkedList<String> months = new LinkedList<>();

// Add all months of a year


months.add("January");
months.add("February");
months.add("March");
months.add("April");
months.add("May");
months.add("June");
months.add("July");
months.add("August");
months.add("September");
months.add("October");
months.add("November");
months.add("December");
// Print the months
System.out.println("Months of the Year:");
for (String month : months) {
System.out.println(month);
}
}
}

6. implement assignment 1 using vector


import java.util.Vector;

public class MonthsVector {


public static void main(String[] args) {

// Create a Vector to store months


Vector<String> months = new Vector<>();

// Add all months of a year


months.add("January");
months.add("February");
months.add("March");
months.add("April");
months.add("May");
months.add("June");
months.add("July");
months.add("August");
months.add("September");
months.add("October");
months.add("November");
months.add("December");

// Print the months


System.out.println("Months of the Year:");
for (String month : months) {
System.out.println(month);
}
}
}

7.Write a program that will have a Vector which is capable of storing Employee
objects. Use an Iterator and enumeration to list all the elements of the Vector.

import java.util.Vector;
import java.util.Iterator;
import java.util.Enumeration;

// Employee class
class Employee {
int empId;
String name;
String email;
double salary;

public Employee(int empId, String name, String email, double salary) {


this.empId = empId;
this.name = name;
this.email = email;
this.salary = salary;
}

@Override
public String toString() {
return "Employee [ID=" + empId + ", Name=" + name +
", Email=" + email + ", Salary=" + salary + "]";
}
}

public class EmployeeVectorDemo {


public static void main(String[] args) {

// Create a Vector to store Employee objects


Vector<Employee> employees = new Vector<>();

// Add some employees


employees.add(new Employee(101, "Alice", "alice@example.com", 50000));
employees.add(new Employee(102, "Bob", "bob@example.com", 60000));
employees.add(new Employee(103, "Charlie", "charlie@example.com", 55000));

// --- Traverse using Iterator ---


System.out.println("Traversing using Iterator:");
Iterator<Employee> it = employees.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

// --- Traverse using Enumeration ---


System.out.println("\nTraversing using Enumeration:");
Enumeration<Employee> en = employees.elements();
while (en.hasMoreElements()) {
System.out.println(en.nextElement());
}
}
}

SET

1. Develop a java class with a instance variable H1 (HashSet) add a method


saveCountryNames (String CountryName) , the method should add the passed country
to a HashSet (H1) and return the added HashSet(H1).
Develop a method getCountry(String CountryName) which iterates through the
HashSet and returns the country if exist else return null.
NOTE: You can test the methods using a main method.

import java.util.HashSet;

public class CountrySet {


private HashSet<String> H1 = new HashSet<>();

public HashSet<String> saveCountryNames(String countryName) {


H1.add(countryName);
return H1;
}

public String getCountry(String countryName) {


for (String country : H1) {
if (country.equalsIgnoreCase(countryName)) {
return country;
}
}
return null;
}

public static void main(String[] args) {


CountrySet cs = new CountrySet();

System.out.println("After adding India : " +


cs.saveCountryNames("India"));
System.out.println("After adding USA : " + cs.saveCountryNames("USA"));
System.out.println("After adding Germany : " +
cs.saveCountryNames("Germany"));
System.out.println("After adding Canada : " +
cs.saveCountryNames("Canada"));

System.out.println("Get 'India' : " + cs.getCountry("India"));


System.out.println("Get 'France' : " + cs.getCountry("France"));

System.out.println("After adding Brazil : " +


cs.saveCountryNames("Brazil"));
}
}

2.Write a program to store a group of employee names into a HashSet, retrieve the
elements one by one using an Iterator.

import java.util.HashSet;
import java.util.Iterator;

public class EmployeeHashSet {


public static void main(String[] args) {
HashSet<String> employees = new HashSet<>();

employees.add("Alice");
employees.add("Bob");
employees.add("Charlie");
employees.add("David");
employees.add("Eve");

System.out.println("Employee Names:");

Iterator<String> it = employees.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}

3.Create a Collection called TreeSet which is capable of storing String objects.


Then try these following operations :
a) Reverse the elements of the Collection.
b) Iterate the elements of the TreeSet using Iterator.
c) Check if a particular element exists or not.

import java.util.Iterator;
import java.util.Scanner;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
// Create a TreeSet to store String objects
TreeSet<String> treeSet = new TreeSet<>();

treeSet.add("Apple");
treeSet.add("Mango");
treeSet.add("Banana");
treeSet.add("Cherry");
treeSet.add("Orange");

System.out.println("Original TreeSet (Sorted Order): " + treeSet);

// (a) Reverse the elements of the Collection


System.out.println("TreeSet in Reverse Order: " + treeSet.descendingSet());

// (b) Iterate the elements of the TreeSet using Iterator


System.out.println("Iterating using Iterator:");
Iterator<String> it = treeSet.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

// (c) Take input from user and check if element exists


Scanner sc = new Scanner(System.in);
System.out.print("Enter element to search: ");
String search = sc.nextLine();

if (treeSet.contains(search)) {
System.out.println(search + " exists in the TreeSet.");
} else {
System.out.println(search + " does not exist in the TreeSet.");
}

sc.close();
}
}

4. implement assignment 1 using TreeSet

import java.util.TreeSet;

public class CountrySet {


private TreeSet<String> H1 = new TreeSet<>();

public TreeSet<String> saveCountryNames(String countryName) {


H1.add(countryName);
return H1;
}

public String getCountry(String countryName) {


for (String country : H1) {
if (country.equalsIgnoreCase(countryName)) {
return country;
}
}
return null;
}
public static void main(String[] args) {
CountrySet cs = new CountrySet();

System.out.println("After adding India : " +


cs.saveCountryNames("India"));
System.out.println("After adding USA : " + cs.saveCountryNames("USA"));
System.out.println("After adding Germany : " +
cs.saveCountryNames("Germany"));
System.out.println("After adding Canada : " +
cs.saveCountryNames("Canada"));

System.out.println("Get 'India' : " + cs.getCountry("India"));


System.out.println("Get 'France' : " + cs.getCountry("France"));

System.out.println("After adding Brazil : " +


cs.saveCountryNames("Brazil"));
}
}

MAP
1. Develop a java class with a instance variable M1 (HashMap) create a method
saveCountryCapital(String CountryName, String capital) , the method should add
the passed country and capital as key/value in the map M1 and return the Map
(M1).
Key- Country Value- Capital
India Delhi
Japan Tokyo
2. Develop a method getCapital(String CountryName) which returns the capital for
the country passed, from the Map M1 created in step 1.
3. Develop a method getCountry(String capitalName) which returns the country for
the capital name, passed from the Map M1 created in step 1.
4. Develop a method which iterates through the map M1 and creates another map M2
with Capital as the key and value as Country and returns the Map M2.
Key - Capital Value-Country
Delhi India
Tokyo Japan
5. Develop a method which iterates through the map M1 and creates an ArrayList
with all the Country names stored as keys. This method should return the
ArrayList.
NOTE: You can test the methods using a main method.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class CountryCapital {


// Instance variable: Country as Key, Capital as Value
private HashMap<String, String> M1 = new HashMap<>();

// 1. Save country and capital into M1


public HashMap<String, String> saveCountryCapital(String countryName, String
capital) {
M1.put(countryName, capital);
return M1;
}

// 2. Get capital for a given country


public String getCapital(String countryName) {
return M1.get(countryName);
}

// 3. Get country for a given capital


public String getCountry(String capitalName) {
for (Map.Entry<String, String> entry : M1.entrySet()) {
if (entry.getValue().equalsIgnoreCase(capitalName)) {
return entry.getKey();
}
}
return null; // If not found
}

// 4. Invert the map: Capital -> Country


public HashMap<String, String> createInvertedMap() {
HashMap<String, String> M2 = new HashMap<>();
for (Map.Entry<String, String> entry : M1.entrySet()) {
M2.put(entry.getValue(), entry.getKey());
}
return M2;
}

// 5. Get all country names as ArrayList


public ArrayList<String> getAllCountries() {
return new ArrayList<>(M1.keySet());
}

// Main method to test


public static void main(String[] args) {
CountryCapital cc = new CountryCapital();

// Step 1: Save countries and capitals


cc.saveCountryCapital("India", "Delhi");
cc.saveCountryCapital("Japan", "Tokyo");

// Print M1
System.out.println("M1 (Country -> Capital): " + cc.M1);

// Step 2: Get capital


System.out.println("Capital of India: " + cc.getCapital("India"));
System.out.println("Capital of Japan: " + cc.getCapital("Japan"));

// Step 3: Get country from capital


System.out.println("Country with capital Delhi: " +
cc.getCountry("Delhi"));
System.out.println("Country with capital Tokyo: " +
cc.getCountry("Tokyo"));

// Step 4: Invert map


HashMap<String, String> M2 = cc.createInvertedMap();
System.out.println("M2 (Capital -> Country): " + M2);

// Step 5: List all countries


ArrayList<String> countryList = cc.getAllCountries();
System.out.println("All Countries: " + countryList);
}
}
2.Create a Collection called HashMap which is capable of storing String objects.
The program should have the following abilities
a) Check if a particular key exists or not.
b) Check if a particular value exists or not.
c) Use Iterator to loop through the map.

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

public class HashMapDemo {


public static void main(String[] args) {
// Create HashMap to store String key-value pairs
HashMap<String, String> map = new HashMap<>();

// Add some sample values


map.put("India", "Delhi");
map.put("Japan", "Tokyo");
map.put("USA", "Washington");
map.put("UK", "London");

// a) Check if a particular key exists


String searchKey = "India";
if (map.containsKey(searchKey)) {
System.out.println("Key \"" + searchKey + "\" exists with value: " +
map.get(searchKey));
} else {
System.out.println("Key \"" + searchKey + "\" does not exist.");
}

// b) Check if a particular value exists


String searchValue = "Tokyo";
if (map.containsValue(searchValue)) {
System.out.println("Value \"" + searchValue + "\" exists in the map.");
} else {
System.out.println("Value \"" + searchValue + "\" does not exist in the
map.");
}

// c) Iterate through the map using Iterator


System.out.println("\nIterating through HashMap:");
Set<Map.Entry<String, String>> entrySet = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();

while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("Key: " + entry.getKey() + ", Value: " +
entry.getValue());
}
}
}
3.Write a program that will have a Properties class object which is capable of
storing some States of India and their Capital. Use an Iterator to list all the
elements stored in the Properties.
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
public class PropertiesDemo {
public static void main(String[] args) {
// Create Properties object
Properties statesAndCapitals = new Properties();

// Store some States and their Capitals


statesAndCapitals.setProperty("Karnataka", "Bengaluru");
statesAndCapitals.setProperty("Maharashtra", "Mumbai");
statesAndCapitals.setProperty("Tamil Nadu", "Chennai");
statesAndCapitals.setProperty("West Bengal", "Kolkata");
statesAndCapitals.setProperty("Uttar Pradesh", "Lucknow");

// Get all the keys (States)


Set<Object> states = statesAndCapitals.keySet();

// Use Iterator to list all entries


System.out.println("States and their Capitals:");
Iterator<Object> iterator = states.iterator();
while (iterator.hasNext()) {
String state = (String) iterator.next();
String capital = statesAndCapitals.getProperty(state);
System.out.println("State: " + state + " -> Capital: " + capital);
}
}
}

4.Create a Collection "ContactList" using HashMap to store name and phone number
of contacts added. The program should use appropriate generics (String, Integer)
and have the following abilities:
a) Check if a particular key exists or not.
b) Check if a particular value exists or not.
c) Use Iterator to loop through the map.

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

public class ContactList {


public static void main(String[] args) {
// Create HashMap with Generics
HashMap<String, Integer> contacts = new HashMap<>();

// Add contacts
contacts.put("Alice", 987654321);
contacts.put("Bob", 912345678);
contacts.put("Charlie", 998877665);
contacts.put("David", 909090909);

// (a) Check if a particular key exists


String searchName = "Alice";
if (contacts.containsKey(searchName)) {
System.out.println(searchName + " exists in Contact List.");
} else {
System.out.println(searchName + " does not exist in Contact List.");
}

// (b) Check if a particular value exists


Integer searchNumber = 912345678;
if (contacts.containsValue(searchNumber)) {
System.out.println("Phone number " + searchNumber + " exists in Contact
List.");
} else {
System.out.println("Phone number " + searchNumber + " does not exist in
Contact List.");
}

// (c) Use Iterator to loop through the map


System.out.println("\nAll Contacts:");
Set<Map.Entry<String, Integer>> entrySet = contacts.entrySet();
Iterator<Map.Entry<String, Integer>> iterator = entrySet.iterator();

while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
System.out.println("Name: " + entry.getKey() + " -> Phone: " +
entry.getValue());
}
}
}

%. Implement 1 using treemap

import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

public class CountryMap {


// Instance variable
private TreeMap<String, String> M1 = new TreeMap<>();

// 1. Save country and capital


public TreeMap<String, String> saveCountryCapital(String countryName, String
capital) {
M1.put(countryName, capital);
return M1;
}

// 2. Get capital for a country


public String getCapital(String countryName) {
return M1.get(countryName);
}

// 3. Get country for a capital


public String getCountry(String capitalName) {
for (Map.Entry<String, String> entry : M1.entrySet()) {
if (entry.getValue().equalsIgnoreCase(capitalName)) {
return entry.getKey();
}
}
return null; // Not found
}

// 4. Reverse map (Capital -> Country)


public TreeMap<String, String> createMapWithCapitalAsKey() {
TreeMap<String, String> M2 = new TreeMap<>();
for (Map.Entry<String, String> entry : M1.entrySet()) {
M2.put(entry.getValue(), entry.getKey());
}
return M2;
}

// 5. Get list of all countries


public ArrayList<String> getAllCountries() {
return new ArrayList<>(M1.keySet());
}

// Main method for testing


public static void main(String[] args) {
CountryMap cm = new CountryMap();

// Add entries
cm.saveCountryCapital("India", "Delhi");
cm.saveCountryCapital("Japan", "Tokyo");
cm.saveCountryCapital("USA", "Washington DC");
cm.saveCountryCapital("UK", "London");

// 2. Get capital
System.out.println("Capital of India: " + cm.getCapital("India"));

// 3. Get country from capital


System.out.println("Country for capital Tokyo: " + cm.getCountry("Tokyo"));

// 4. Reverse map
TreeMap<String, String> M2 = cm.createMapWithCapitalAsKey();
System.out.println("\nM2 (Capital -> Country):");
for (Map.Entry<String, String> entry : M2.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}

// 5. Get all countries


System.out.println("\nAll countries: " + cm.getAllCountries());
}
}
6. implement1 using Hastable
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;

public class CountryHashtable {


// Instance variable
private Hashtable<String, String> M1 = new Hashtable<>();

// 1. Save country and capital


public Hashtable<String, String> saveCountryCapital(String countryName, String
capital) {
M1.put(countryName, capital);
return M1;
}

// 2. Get capital for a country


public String getCapital(String countryName) {
return M1.get(countryName);
}

// 3. Get country for a capital


public String getCountry(String capitalName) {
for (Map.Entry<String, String> entry : M1.entrySet()) {
if (entry.getValue().equalsIgnoreCase(capitalName)) {
return entry.getKey();
}
}
return null; // Not found
}

// 4. Reverse map (Capital -> Country)


public Hashtable<String, String> createMapWithCapitalAsKey() {
Hashtable<String, String> M2 = new Hashtable<>();
for (Map.Entry<String, String> entry : M1.entrySet()) {
M2.put(entry.getValue(), entry.getKey());
}
return M2;
}

// 5. Get list of all countries


public ArrayList<String> getAllCountries() {
return new ArrayList<>(M1.keySet());
}

// Main method for testing


public static void main(String[] args) {
CountryHashtable ch = new CountryHashtable();

// Add entries
ch.saveCountryCapital("India", "Delhi");
ch.saveCountryCapital("Japan", "Tokyo");
ch.saveCountryCapital("USA", "Washington DC");
ch.saveCountryCapital("UK", "London");

// 2. Get capital
System.out.println("Capital of India: " + ch.getCapital("India"));

// 3. Get country from capital


System.out.println("Country for capital Tokyo: " + ch.getCountry("Tokyo"));

// 4. Reverse map
Hashtable<String, String> M2 = ch.createMapWithCapitalAsKey();
System.out.println("\nM2 (Capital -> Country):");
for (Map.Entry<String, String> entry : M2.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}

// 5. Get all countries


System.out.println("\nAll countries: " + ch.getAllCountries());
}
}

Lambda Expressions

2.
Create an ArrayList al and add 10 different words.
Write a code to print all the Strings in reverse order, using lambda expression.

import java.util.ArrayList;
import java.util.Collections;
public class ReverseArrayListLambda {
public static void main(String[] args) {
// Create ArrayList and add 10 words
ArrayList<String> al = new ArrayList<>();
al.add("Apple");
al.add("Banana");
al.add("Cherry");
al.add("Dragonfruit");
al.add("Elderberry");
al.add("Fig");
al.add("Grapes");
al.add("Honeydew");
al.add("Kiwi");
al.add("Lemon");

// Print in reverse order using lambda


System.out.println("Words in reverse order:");
Collections.reverse(al);
al.forEach(word -> System.out.println(word));
}
}
4. Create an interface WordCount with a single abstract method int count(String
str), to count and return the no of words in the given String.
Implement count method using Lambda expression in another class
MyClassWithLambda.
Invoke it to display the result on the console.

// Step 1: Create the functional interface


@FunctionalInterface
interface WordCount {
int count(String str);
}

// Step 2: Implement using Lambda in another class


public class MyClassWithLambda {
public static void main(String[] args) {

// Lambda implementation of WordCount


WordCount wc = (str) -> {
if (str == null || str.trim().isEmpty()) {
return 0; // No words if string is empty
}
String[] words = str.trim().split("\\s+"); // split by one or more
spaces
return words.length;
};

// Step 3: Invoke and display result


String input = "Java makes lambda expressions easy to use";
System.out.println("Input String: " + input);
System.out.println("Word Count: " + wc.count(input));
}
}

Method Reference
3.
Define your own class and a parameterized constructor with one integer
argument. It should check the argument and display "Prime" or "Not Prime".
Define your own functional interface to refer this constructor and invoke it to
check whether the given number is Prime or Not.

// Step 1: Define functional interface


@FunctionalInterface
interface NumberChecker {
void check(int num);
}

// Step 2: Define class with parameterized constructor


class PrimeCheck {
PrimeCheck(int num) {
if (isPrime(num)) {
System.out.println(num + " is Prime");
} else {
System.out.println(num + " is Not Prime");
}
}

// Utility method to check prime


private boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
}

// Step 3: Test using Constructor Reference


public class Main {
public static void main(String[] args) {
// Constructor reference
NumberChecker checker = PrimeCheck::new;

// Invoke constructor via functional interface


checker.check(7); // Prime
checker.check(10); // Not Prime
checker.check(1); // Not Prime
}
}

Stream API

3.
Create a Student class with
1. Instance variables: rollNo, name, mark.
2. A parameterized constructor to initialize them.

Write a program
1. To add five Student objects into and ArrayList,
2. Filter the Student objects who have cleared the test with minimum 50 marks,
3. Get the count of how many have cleared and print it.

import java.util.*;
import java.util.stream.*;

class Student {
int rollNo;
String name;
int mark;

// Parameterized constructor
public Student(int rollNo, String name, int mark) {
this.rollNo = rollNo;
this.name = name;
this.mark = mark;
}

@Override
public String toString() {
return rollNo + " - " + name + " - " + mark;
}
}

public class StudentTest {


public static void main(String[] args) {
// Step 1: Add 5 students to ArrayList
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(1, "Alice", 45));
students.add(new Student(2, "Bob", 60));
students.add(new Student(3, "Charlie", 30));
students.add(new Student(4, "David", 85));
students.add(new Student(5, "Eva", 55));

// Step 2: Filter students who cleared (mark >= 50)


List<Student> cleared = students.stream()
.filter(s -> s.mark >= 50)
.collect(Collectors.toList());

// Step 3: Get count


long count = cleared.size();

// Print results
System.out.println("Students who cleared (marks >= 50):");
cleared.forEach(System.out::println);

System.out.println("Total cleared: " + count);


}
}

Functional Interface

3. Given an ArrayList containing 10 words, write a program to filter the words


which are palindrome, with the help of Predicate.

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PalindromeFilter {


public static void main(String[] args) {
// Step 1: Create ArrayList with 10 words
ArrayList<String> words = new ArrayList<>(Arrays.asList(
"madam", "apple", "racecar", "hello", "level",
"world", "noon", "java", "civic", "book"
));
// Step 2: Define Predicate to check palindrome
Predicate<String> isPalindrome = word ->
word.equalsIgnoreCase(new StringBuilder(word).reverse().toString());

// Step 3: Filter palindromes using Predicate


List<String> palindromes = words.stream()
.filter(isPalindrome)
.collect(Collectors.toList());

// Step 4: Print results


System.out.println("Palindrome words: " + palindromes);
}
}

7.
Given an ArrayList containing 10 numbers, write a program using Consumer
methods to display each number and whether is it odd or even.
Example: For number 2, it should print "2 even" For number 5, it should print "5
odd"
import java.util.*;
import java.util.function.Consumer;

public class OddEvenConsumer {


public static void main(String[] args) {
// Step 1: Create an ArrayList with 10 numbers
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
));

// Step 2: Define Consumer to check odd/even


Consumer<Integer> checkOddEven = num -> {
if (num % 2 == 0) {
System.out.println(num + " even");
} else {
System.out.println(num + " odd");
}
};

// Step 3: Use forEach with Consumer


numbers.forEach(checkOddEven);
}
}
8.
Write a program using Supplier, which generates and returns an ArrayList
containing first 10 prime numbers.

import java.util.ArrayList;
import java.util.function.Supplier;

public class PrimeSupplier {

// Utility method to check if a number is prime


private static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}

public static void main(String[] args) {

// Supplier that generates first 10 prime numbers


Supplier<ArrayList<Integer>> primeSupplier = () -> {
ArrayList<Integer> primes = new ArrayList<>();
int count = 0, num = 2;
while (count < 10) {
if (isPrime(num)) {
primes.add(num);
count++;
}
num++;
}
return primes;
};

// Get the list from supplier


ArrayList<Integer> primeList = primeSupplier.get();

// Print the result


System.out.println("First 10 Prime Numbers: " + primeList);
}
}

Date Time API

4. Write a program to check weather the current year is a leap year

import java.time.Year;

public class LeapYearCheck {


public static void main(String[] args) {
// Get current year
int currentYear = Year.now().getValue();

// Check leap year condition


boolean isLeap = (currentYear % 400 == 0) || (currentYear % 4 == 0 &&
currentYear % 100 != 0);

// Print result
System.out.println("Current Year: " + currentYear);
if (isLeap) {
System.out.println(currentYear + " is a Leap Year");
} else {
System.out.println(currentYear + " is NOT a Leap Year");
}
}
}

You might also like