0% found this document useful (0 votes)
4 views

Java Lab Report Book Sem2 2025

The document provides a detailed guide on creating and manipulating ArrayLists and Maps in Java, including sorting with a Comparator and iterating with an Iterator. It includes example programs for sorting items by price, removing expired products, and managing country codes with a Map. Additionally, it covers data persistence using Properties and file I/O for saving and loading configuration settings.

Uploaded by

itsmeaung01
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Lab Report Book Sem2 2025

The document provides a detailed guide on creating and manipulating ArrayLists and Maps in Java, including sorting with a Comparator and iterating with an Iterator. It includes example programs for sorting items by price, removing expired products, and managing country codes with a Map. Additionally, it covers data persistence using Properties and file I/O for saving and loading configuration settings.

Uploaded by

itsmeaung01
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

LAB-I

ARRAYLIST SORTING AND ITERATING

OBJECTIVES:
 To understand how to create ArrayList collection is java.
 To write a program that uses comparator interface to sort the collection.
 To write a program that transverse an ArrayList while safely removing
elements from it.

DESCRIPTION:
 ArrayList: A resizable array implementation of List that allows dynamic
storage, fast random access, and maintains insertion order. It supports adding,
removing, and retrieving elements efficiently.
 Comparator: An interface that defines custom sorting logic for objects. It is
used with Collections.sort() or List.sort() to specify sorting rules based on
custom criteria.
 Iterator: An object used to traverse collections like ArrayList sequentially
without exposing internal structure. It provides methods like hasNext(), next(),
and remove() for safe iteration.

/*Sorting an ArrayList using Comparator Interface*/


1. Write a java application that sort the following item list based on their unit price in
descending order. Create a class named Item that has three instance variables: ID,
itemName, and price. Use ArrayList to store item objects, sort the ArrayList by
implementing comparator interface and display the result.

ID Product Name Price


1 HDMI cable 10.99
2 USB Hub 25.8
3 Mouse Pad 6.5
4 Wireless Mouse 31.99

Program:

//Item.java

public class Item {

public int ID;

public String productName;

public double price;

public Item(int id, String name, double p) {

1|Page
ID = id;

productName = name;

price = p;

// PriceComparator.java

import java.util.*;

public class PriceComparator implements Comparator<Item> {

public int compare(Item a, Item b) {

int result;

if(a.price > b.price) {

result = -1;

}else if(a.price < b.price){

result = 1;

}else {

result = 0;

return result;

//InvoiceDisplay.java

import java.util.*;

public class InvoiceDisplay {

public static ArrayList<Item> products = new ArrayList<Item>();

public static void main(String[] args) {

products.add(new Item(1,"HDMI cable",10.99));

products.add(new Item(2,"USB Hub",25.8));

2|Page
products.add(new Item(3,"Mouse Pad",6.5));

products.add(new Item(4,"Wireless mouse",31.99));

System.out.print("Invoice list\n");

DisplayList();

System.out.print("\nInvoice list sorted in descending unit price\n");

Collections.sort(products,new PriceComparator());

DisplayList();

public static void DisplayList() {

System.out.printf("%3s %-20s %s \n\n","ID","Product","Price");

for(Item i : products) {

System.out.printf("%3d %-20s %.2f \n",i.ID,i.productName,i.price);

Output:

3|Page
/*Tranversing the ArrayList using Iterator Object*/
2. Write a java program to display a list of food products and remove the expired
products. Create a class named Product which has two instance variable:
productName and expireYear. Use an ArrayList to store the products provided in the
following table. Use Iterator object to loop through the ArrayList and remove any
product that has their expire year equal or greater than the number entered by the user.

ID Product Name EXP Year


1 Instant Coffee 2019
2 Rice 2027
3 Floor 2025
4 Sugar 2022
5 Powdered Milk 2021
6 Honey 2050

Program:
//Product.java
public class Product {
public int ID;
public String productName;
public int expire;
public Product(int id, String name, int exp) {
ID = id;
productName = name;
expire = exp;
}
}
//ProductDisplay.java
import java.util.*;
public class ProductDisplay {

public static ArrayList<Product> products = new ArrayList<Product>();


public static void main(String[] args) {

4|Page
products.add(new Product(1,"Instant Coffee", 2019) );
products.add(new Product(2,"Rice", 2027) );
products.add(new Product(3,"Flour", 2025) );
products.add(new Product(4,"Sugar", 2022) );
products.add(new Product(5,"Powdered Milk", 2021) );
products.add(new Product(6,"Honey", 2050) );

DisplayList();
System.out.print("\nEnter a date to remove expired products: ");
Scanner input = new Scanner(System.in);
int year = input.nextInt();

Iterator<Product> iterator = products.iterator();


while(iterator.hasNext()) {
Product p = iterator.next();
if(p.expire < year) {
iterator.remove();
}
}
System.out.printf("\nRemoved products with exp date in %s and before\n",
year);
DisplayList();

}
public static void DisplayList() {
System.out.printf("%3s %-20s %-10s \n\n","ID","Product", "EXP Year");
for(Product i : products) {
System.out.printf("%3d %-20s %-10d \n",i.ID,i.productName, i.expire);
}
}

5|Page
}

Output:

6|Page
LAB – II
Key-Value Data Structures

OBJECTIVES:
 To understand how a Map collection and Properties class are used to associate
keys with values.
 To write a program that persists data by saving and loading using file input
and output streams.

DESCRIPTION
 Map: A key-value data structure in Java that allows efficient storage and
retrieval of data. Implementations like HashMap and TreeMap provide
different performance characteristics for storing and managing key-value
pairs.

 Properties: A subclass of Hashtable specifically designed to store key-value


pairs as String keys and values. It is commonly used for configuration settings
and supports loading and saving data using files IO streams

1. Create a java program that display a list of country names with their corresponding
two letter country codes provided in the following table. Use a Map collection to store
country codes as key and country name as value. The program should also have a
functionality where users can update the list by adding a new pair of key and value.

Country
Country Name
Code
US United States
CN China
JP Japan
RU Russia
KR South Korea

Program:
import java.util.*;
public class CountryCodeTest {
public static Map<String,String> countries = new HashMap<>();

7|Page
public static void main(String[] args) {
countries.put("US", "United States");
countries.put("CN", "China");
countries.put("JP", "Japan");
countries.put("RU", "Russia");
countries.put("KR", "South Korea");

Scanner input = new Scanner(System.in);


displayMap();
userInput(input);

}
public static void userInput(Scanner input) {
while(true) {
System.out.print("\nEnter a new country code to add (empty to exit): ");
String code = input.nextLine().toUpperCase();
if(code.isEmpty()) {
System.out.print("Program terminated!");
break;
}
if(countries.containsKey(code)) {
System.out.printf("Country code for %s already exist!\
n",countries.get(code));
continue;
}else {
System.out.print("Enter country name: ");
String fullName = input.nextLine();
countries.put(code, fullName);
}
displayMap();

8|Page
}// while loop
}// userInput Method
public static void displayMap() {
System.out.printf("\n%-10s %-10s","CODE", "COUNTRY NAME\n\n");
for(String key : countries.keySet()) {
String value = countries.get(key);
System.out.printf("%-10s %-10s\n",key, value);
}
}
}

Output:

*/Data Persistence with Properties and File IO in Java*/


2. Write an application to create a properties table and display the information in it.
The program should ask the user whether to create a new properties table or to load an
existing file form disk. If the user choose to create, initialize a properties table with
the information provided in the following and save it as a file into the disk. If user
choose to load, read the created file from disk and display it as a properties table.
#Server Config
host=localhost
level=DEBUG
password=1234
port=800
9|Page
username=root

Program:
import java.io.*;
import java.util.*;
public class PropertiesTest {
public static void main(String[] args) {
Properties table = new Properties();

System.out.print("1.Create Table 2.Load Table: ");


Scanner input = new Scanner(System.in);
int option = Integer.parseInt(input.nextLine());
if(option == 1) {

table.setProperty("port","800");
table.setProperty("host","localhost");
table.setProperty("username","root");
table.setProperty("password","1234");
table.setProperty("level","DEBUG");
saveFile(table);
}
if(option == 2) {
loadFile(table);
}

}
public static void loadFile(Properties table) {
try {
FileInputStream file = new FileInputStream("props.ini");
table.load(file);
file.close();
System.out.print("\nFile Loaded!");
displayTable(table);
}catch(IOException e) {
System.out.print("\nFailed to load file!");
e.printStackTrace();
}
}
public static void saveFile(Properties table) {
try {
displayTable(table);
FileOutputStream file = new FileOutputStream("props.ini");
table.store(file, "Server Config");
file.close();

10 | P a g e
System.out.print("\nFile Saved!");
}catch(IOException e) {
System.out.print("\nFailed to save file!");
e.printStackTrace();
}
}
public static void displayTable(Properties table) {
System.out.print("\n----Properties Table----\n");
for(Object key : table.keySet()) {
String value = table.getProperty((String)key);
System.out.printf("%-10s %-10s\n",key, value);
}
}
}

Output:

11 | P a g e

You might also like