Snippets Collections
// use while loops when the number of items we are looping over are unknown


let items = [
  { id: 1, name: "Item 1", price: 10.99 },
  { id: 2, name: "Item 2", price: 15.49 },
  { id: 3, name: "Item 3", price: 7.99 },
  { id: 4, name: "Item 4", price: 12.0 },
  { id: 5, name: "Item 5", price: 9.5 },
];

let i = 0; // counter variable

let numberOfItems = items.length ?? 0; // if the number of items is not a number give me 0;
console.log(numberOfItems);

while (i < items.length) {
  let { id, name, price } = items[i]; // Destructuring assignment
  console.log(`ID: ${id}, Name: ${name}, Price: $${price}`);
  i++;
}
CREATE TABLE `user_activity` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(150) DEFAULT NULL,
  `login_time` datetime DEFAULT NULL,
  `logout_time` datetime DEFAULT NULL,
  `path_info` varchar(255) DEFAULT NULL,
  `api_hit` tinyint(1) DEFAULT '0',
  `response_time` bigint DEFAULT NULL,
  `ip_address` varchar(45) DEFAULT '',
  `timestamp` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=117382 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;


CREATE TABLE `user_session` (
  `id` int NOT NULL AUTO_INCREMENT,
  `username` varchar(150) DEFAULT '',
  `login_time` datetime NOT NULL,
  `logout_time` datetime DEFAULT NULL,
  `session_duration_seconds` int DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=98 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
 1class ContactForm extends Component
 2{
 3    public $name;
 4    public $email;
 5 
 6    protected $rules = [
 7        'name' => 'required|min:6',
 8        'email' => 'required|email',
 9    ];
10 
11    public function updated($propertyName)
12    {
13        $this->validateOnly($propertyName);
14    }
15 
16    public function saveContact()
17    {
18        $validatedData = $this->validate();
19 
20        Contact::create($validatedData);
21    }
22}
gcloud compute ssh --zone YOUR_ZONE YOUR_INSTANCE_NAME -- -L 8888:localhost:8888
    
1<div>
2    <input wire:model="message" type="text">
3 
4    <h1>{{ $message }}</h1>
5</div>

//data binding 
 1public $search = '';
 2public $isActive = true;
 3 
 4public function resetFilters()
 5{
 6    $this->reset('search');
 7    // Will only reset the search property.
 8 
 9    $this->reset(['search', 'isActive']);
10    // Will reset both the search AND the isActive property.
11 
12    $this->resetExcept('search');
13    // Will only reset the isActive property (any property but the search property).
14}
1class HelloWorld extends Component
2{
3    public $message;
4       //initializing properties witht the property
5    public function mount()
6    {
7        $this->message = 'Hello World!';
8    }
9}
 1public $search = '';
 2public $isActive = true;
 3 
 4public function resetFilters()
 5{
 6    $this->reset('search');
 7    // Will only reset the search property.
 8 
 9    $this->reset(['search', 'isActive']);
10    // Will reset both the search AND the isActive property.
11 
12    $this->resetExcept('search');
13    // Will only reset the isActive property (any property but the search property).
14}
<script>
  async function harryPotterStudents() {
      const res = await fetch('https://hp-api.herokuapp.com/api/characters/students');
      const json = await res.json()

      if (res.ok) {
          return json
      } else {
          throw new Error(json)
      }
  }

  let promise = harryPotterStudents()
</script>

<h2>Estudiantes de la saga Harry Potter (promesas)</h2>
{#await promise}
  <p>Esperando resultados...</p>
{:then students}
  <p>Total estudiantes: {students.length}</p>
  {#each students as {name: alt, house, image: src}}
    {#if src}
      <h3>{alt} ({house})</h3>
      <img height="100" {src} {alt} />
    {/if}
  {/each}
{:catch error}
  <p style="color: red">{error.message}</p>
{/await}
declare 
   invalid_sal Exception;
   s employee.sal%type:=&sal;
begin 
   if (s<3000) then
     raise invalid_sal;
   else
     insert into employee(sal) values(s);
     dbms_output.put_line('Record inserted');
   end if;
Exception
      when invalid_sal then
           dbms_output.put_line('sal greater ');
end;
/
/*
 * @Author: allen_
 * @Date: 2024-05-22 10:45:18
 * @Email: zhangxudong_a@aspirecn.com
 * @LastEditors: allen_
 * @LastEditTime: 2024-05-23 15:43:17
 * @Description: 水印
 * @example:
 *   watermark.set(this.$refs.body, { text: '水印文字', gap: [50, 100], fontSize: 14, color: 'rgba(0, 0, 0, 0.35)'})
 */
import html2canvas from 'html2canvas'
const watermark = {}

/**
 * @description: 设置水印
 * @param {*} sourceBody 需要设置的元素
 * @param {*} text 水印文字
 * @param {array} gap 水印间距 [上下间距, 左右间距]
 * @param {*} fontSize 水印文字大小
 * @param {*} color 水印字体颜色
 * @param {*} zIndex 水印层级
 * @param {*} rotate 水印角度
 */
const setWatermark = (sourceBody, { text = 'watermark', gap = [100, 120], fontSize = 14, color = 'rgba(0, 0, 0, 0.25)', zIndex = 9999, rotate = -22, custom = null }) => {
  // @Explain: 生成随机元素 id
  const id = Math.random() * 10000 + '-' + Math.random() * 10000 + '/' + Math.random() * 10000

  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id))
  }
  let canvasData = null
  if (!custom) {
    const can = document.createElement('canvas')
    can.height = gap[0] // 水印上下间距
    can.width = gap[1] // 水印左右间距

    const cans = can.getContext('2d')
    cans.rotate((rotate * Math.PI) / 180)
    cans.font = fontSize + 'px Microsoft YaHei'
    cans.fillStyle = color
    cans.textAlign = 'left'
    cans.textBaseline = 'Middle'
    cans.fillText(text, can.width / 20, can.height / 3)
    canvasData = can.toDataURL('image/png', 1.0)
  } else {
    canvasData = custom
  }

  const water_div = document.createElement('div')
  water_div.id = id
  water_div.className = 'watermark-body'
  const styleStr = `
    background: url(${canvasData}) left top repeat;
    pointer-events: none;
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: ${zIndex};
    top: 0px;
    left: 0px;
  `
  water_div.setAttribute('style', styleStr)
  const partnerStyle = `
    ${sourceBody.getAttribute('style') || ''}
    position: relative;
    userSelect: none;
  `
  sourceBody.setAttribute('style', partnerStyle)
  sourceBody.appendChild(water_div)

  // 防止水印被删除
  const observer = new MutationObserver(() => {
    const wmInstance = document.getElementById(id)
    if ((wmInstance && wmInstance.getAttribute('style') !== styleStr) || !wmInstance) {
      // 如果标签在,只修改了属性,重新赋值属性
      if (wmInstance) {
        // 避免一直触发 -- 水印属性修改了
        wmInstance.setAttribute('style', styleStr)
      } else {
        // observer.disconnect()
        sourceBody.appendChild(water_div)
      }
    } else if (sourceBody.getAttribute('style') !== partnerStyle) {
      // @Explain: 判断父元素样式是否存在更改
      sourceBody.setAttribute('style', partnerStyle)
    }
  })
  observer.observe(sourceBody, {
    attributes: true,
    subtree: true,
    childList: true
  })

  return id
}

// @Explain: 为元素设置水印
watermark.set = (sourceBody, opi) => {
  const domArr = Array.from(document.getElementsByClassName('watermark-body'))
  for (let i = domArr.length; i--;) {
    const element = domArr[i]
    element.remove()
  }
  if ((!opi.text && !opi.custom) || !sourceBody) return null
  if (!(sourceBody instanceof HTMLElement)) {
    // @Condition: 判断传入的元素是否为dom元素 || VueComponent
    sourceBody = sourceBody.$el
  }
  const id = setWatermark(sourceBody, opi)
  return id
}
// @Explain: html2canvas 创建元素 base64
watermark.baseImg = (el, scale = window.devicePixelRatio < 3 ? window.devicePixelRatio : 2) => {
  return new Promise((resolve) => {
    html2canvas(el, {
      useCORS: true, // 【重要】开启跨域配置
      scale,
      allowTaint: true, // 允许跨域图片
      backgroundColor: null // 是否设置背景色透明
    }).then((canvas) => {
      const imgData = canvas.toDataURL('img/jpg', 1.0)
      resolve(imgData)
    })
  })
}
// @Explain: 创建水印方法
watermark.create = (text = 'watermark', callback = null, cache = true) => {
  if (callback && typeof callback === 'function') {
    // @Condition: 自定义水印元素创建方法
    return callback(text, watermark)
  }
  // @Explain: 判断缓存创建的水印元素是否存在
  if (watermark.cacheEl && cache) {
    watermark.cacheEl.querySelector('.watermark-user-info').innerText = text
    return watermark.cacheEl
  }
  const div = document.createElement('div')
  div.style = `
    width: 200px;
    height: 160px;
    display: flex;
    align-items: center;`
  const watermarkDiv = document.createElement('div')
  watermarkDiv.style = `
    width: 210px;
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    transform-origin: center;
    transform: rotate(-35deg);`
  const img = document.createElement('img')
  img.style = 'width: 201px;'
  // if you need image, edit here
  // img.src = require('@/assets/img/watermark.png')
  const userInfo = document.createElement('div')
  userInfo.className = 'watermark-user-info'
  userInfo.style = `
    font-size: 12px;
    color: rgba(38, 42, 48, 0.1);
    letter-spacing: 0;
    font-family: PingFangSC-Regular;`
  userInfo.innerText = text
  watermarkDiv.appendChild(img)
  watermarkDiv.appendChild(userInfo)
  div.appendChild(watermarkDiv)
  watermark.cacheEl = div // 缓存水印元素
  return div
}

export default watermark
Things to keep in Mind in Linked List
1) Make sure where to use temp->next1=NULL  OR temp!=NULL
2) fast!=NULL && fast->next!=NULL 
Use this order only else it will give runtime error
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useLocation } from "react-router-dom";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import "bootstrap/dist/css/bootstrap.min.css";
import Header from "../Header.jsx";
import Footer from "../Footer.jsx";
import { FaMapMarkerAlt, FaStar, FaUserMd } from "react-icons/fa"; // Импортируем иконки
import doctorImg from "../Assets/dc1.png";

const SpecificClinicPage = () => {
    const location = useLocation();
    const [clinic, setClinic] = useState(null);
    const [doctors, setDoctors] = useState([]);
    const [services, setServices] = useState([]);

    useEffect(() => {
        const fetchClinic = async () => {
            try {
                const id = new URLSearchParams(location.search).get("id");
                if (!id) {
                    throw new Error("Clinic ID not provided");
                }
                const response = await axios.get(
                    `http://localhost:8000/clinic?id=${id}`
                );
                setClinic(response.data);

                const doctorsResponse = await axios.get(
                    `http://localhost:8000/get-clinic-doctors?id=${id}`
                );
                setDoctors(doctorsResponse.data);

                // Fetch services for the clinic
                const servicesResponse = await axios.get(
                    `http://localhost:8000/get-clinic-services?id=${id}`
                );
                setServices(servicesResponse.data);
            } catch (error) {
                console.error("Error fetching clinic:", error);
            }
        };
        fetchClinic();
    }, [location.search]);

    const sliderSettings = {
        dots: true,
        infinite: true,
        speed: 500,
        slidesToShow: 3,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 3000,
        responsive: [
            {
                breakpoint: 1024,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 1,
                    infinite: true,
                    dots: true
                }
            },
            {
                breakpoint: 600,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1
                }
            }
        ]
    };

    return (
        <div style={{ display: "flex", flexDirection: "column", minHeight: "100vh" }}>
            <Header />
            <style>{styles}</style>
            <div
                style={{
                    display: "flex",
                    flexDirection: "column",
                    minHeight: "100vh",
                    backgroundImage: 'url("/clinic1.png")',
                    backgroundSize: "cover",
                    color: "white",
                }}
            >
                <div style={{ marginLeft: "300px", marginTop: "100px" }}>
                    <p
                        style={{
                            fontSize: "90px",
                            fontWeight: "600",
                            marginRight: "400px",
                        }}
                    >
                        {"clinic.clinic_name"}
                    </p>
                    <p style={{ fontSize: "29px", maxWidth: "900px", fontWeight: "400" }}>
                        {"clinic.description"}
                    </p>
                    <p style={{ fontSize: "34px", fontWeight: "600" }}>
                        <FaMapMarkerAlt /> <strong>Address:</strong> {"clinic.address"}
                    </p>
                </div>
            </div>

            {/* Карусель "Услуги клиники" */}
            <div style={{ textAlign: "center", marginTop: "60px", marginBottom: "40px" }}>
                <p style={{ color: "#00145B", fontSize: "60px" }}>Услуги клиники</p>
            </div>

            <div className="slider-container">
                <Slider {...sliderSettings}>
                    {services.map(service => (
                        <div className="slider-item" key={service.id}>
                            <div className="service-icons"> {/* Добавляем контейнер для иконок */}
                                <FaUserMd className="icon" /> {/* Иконка доктора */}
                            </div>
                            <h3>{service.name}</h3>
                            <p>{service.description}</p>
                            <button className="service-button">Записаться</button>
                        </div>
                    ))}
                </Slider>
            </div>

            {/* Карусель "Доктора в клинике" */}
            <div style={{ textAlign: "center", marginTop: "60px", marginBottom: "40px" }}>
                <p style={{ color: "#00145B", fontSize: "60px" }}>Доктора в клинике</p>
            </div>

            <div className="slider-container" style={{ marginBottom: "60px" }}>
                <Slider {...sliderSettings}>
                    {doctors.map(doctor => (
                        <div className="slider-item" key={doctor.id}>
                            <img
                                src={doctorImg}
                                alt={doctor.name}
                                style={{ marginLeft: "95px", width: "50%", height: "auto", maxHeight: "200px" }}
                            />
                            <h3>{doctor.name}</h3>
                            <p>{doctor.type}</p>
                        </div>
                    ))}
                </Slider>
            </div>

            <Footer />
        </div>
    );
};

export default SpecificClinicPage;

const styles = `
    .slider-container {
        width: 70%;
        margin: 0 auto;
    }

    .slider-item {
        text-align: center;
        padding: 20px;
        /* border: 1px solid #ddd; Убрали границу */
        border-radius: 5px;
        background-color: #fff;
        position: relative; /* Добавляем позиционирование */
        margin: 0 10px; /* Добавляем отступы для выравнивания расстояния */
        box-sizing: border-box; /* Убедимся, что padding и border не влияют на ширину */
    }

    .slider-item h3 {
        font-size: 24px;
        color: #00145B;
        margin-bottom: 10px;
    }

    .slider-item p {
        font-size: 16px;
        color: #555;
        margin-bottom: 20px;
    }

    .slider-item img {
        width: 100%;
        height: auto;
        max-height: 200px;
        border-radius: 5px;
        margin-bottom: 10px;
    }

    .service-icons {
        display: flex;
        margin-top: 10px;
        margin-bottom: 10px;
    }

    .service-icons .icon {
        font-size: 60px;
        color: #33437C;
        margin-left: 170px;
    }

    .service-button {
        background-color: #2A65FF;
        color: #fff;
        border: none;
        padding: 15px 90px;
        font-size: 24px;
        cursor: pointer;
        transition: background-color 0.3s;
        margin-top: 20px;
    }

    .service-button:hover {
        background-color: #0043b2;
    }
    /* Стили для точек пагинации */
    .slick-dots li button:before {
    margin-top: 10px;
    font-size: 16px;
    color: #2A65FF;
}

    .slick-dots li.slick-active button:before {
    color: #0043b2;
}
/* Обертка для слайдера */
    .slick-slider {
    margin: 0 auto;
    padding: 0 20px;
}
`
// SpecificClinicPage.jsx

import React, { useState, useEffect } from "react";
import axios from "axios";
import { useLocation } from "react-router-dom";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import "bootstrap/dist/css/bootstrap.min.css";
import Header from "../Header.jsx";
import Footer from "../Footer.jsx";
import { FaMapMarkerAlt } from "react-icons/fa";
import doctorImg from "../Assets/doctor3.png";

const SpecificClinicPage = () => {
    const location = useLocation();
    const [clinic, setClinic] = useState(null);
    const [doctors, setDoctors] = useState([]);
    const [services, setServices] = useState([]);

    useEffect(() => {
        const fetchClinic = async () => {
            try {
                // Тестовые данные для услуг клиники
                const testServices = [
                    { id: 1, name: "Service 1", description: "Description for service 1" },
                    { id: 2, name: "Service 2", description: "Description for service 2" },
                    { id: 3, name: "Service 3", description: "Description for service 3" },
                ];

                // Тестовые данные для докторов в клинике
                const testDoctors = [
                    { id: 1, name: "Doctor 1", type: "Type 1" },
                    { id: 2, name: "Doctor 2", type: "Type 2" },
                    { id: 3, name: "Doctor 3", type: "Type 3" },
                ];

                setServices(testServices);
                setDoctors(testDoctors);
            } catch (error) {
                console.error("Error fetching clinic:", error);
            }
        };
        fetchClinic();
    }, []);

    const sliderSettings = {
        dots: true,
        infinite: true,
        speed: 500,
        slidesToShow: 3,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 3000,
        responsive: [
            {
                breakpoint: 1024,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 1,
                    infinite: true,
                    dots: true
                }
            },
            {
                breakpoint: 600,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1
                }
            }
        ]
    };

    return (
        <div style={{ display: "flex", flexDirection: "column", minHeight: "100vh" }}>
            <Header />
            <style>{styles}</style>
            <div
                style={{
                    display: "flex",
                    flexDirection: "column",
                    minHeight: "100vh",
                    backgroundImage: 'url("/clinic1.png")',
                    backgroundSize: "cover",
                    color: "white",
                }}
            >
                <div style={{ marginLeft: "300px", marginTop: "100px" }}>
                    <p
                        style={{
                            fontSize: "90px",
                            fontWeight: "600",
                            marginRight: "400px",
                        }}
                    >
                        {"clinic.clinic_name"}
                    </p>
                    <p style={{ fontSize: "29px", maxWidth: "900px", fontWeight: "400" }}>
                        {"clinic.description"}
                    </p>
                    <p style={{ fontSize: "34px", fontWeight: "600" }}>
                        <FaMapMarkerAlt /> <strong>Address:</strong> {"clinic.address"}
                    </p>
                </div>
            </div>

            <div style={{ textAlign: "center", marginTop: "60px", marginBottom: "40px" }}>
                <p style={{ color: "#00145B", fontSize: "60px" }}>Услуги клиники</p>
            </div>

            <div className="slider-container">
                <Slider {...sliderSettings}>
                    {services.map(service => (
                        <div className="slider-item" key={service.id}>
                            <h3>{service.name}</h3>
                            <p>{service.description}</p>
                            <button className="service-button">Записаться</button>
                        </div>
                    ))}
                </Slider>
            </div>

            <div style={{ textAlign: "center", marginTop: "60px", marginBottom: "40px" }}>
                <p style={{ color: "#00145B", fontSize: "60px" }}>Доктора в клинике</p>
            </div>

            <div className="slider-container" style={{ marginBottom: "60px" }}>
                <Slider {...sliderSettings}>
                    {doctors.map(doctor => (
                        <div className="slider-item" key={doctor.id}>
                            <img
                                src={doctorImg}
                                alt={doctor.name}
                                style={{ width: "100%", height: "auto", maxHeight: "200px" }}
                            />
                            <h3>{doctor.name}</h3>
                            <p>{doctor.type}</p>
                        </div>
                    ))}
                </Slider>
            </div>

            <Footer />
        </div>
    );
};

export default SpecificClinicPage;

const styles = `
    .slider-container {
        width: 70%;
        margin: 0 auto;
    }

    .slider-item {
        text-align: center;
        padding: 20px;
        border: 1px solid #ddd;
        border-radius: 5px;
        background-color: #fff;
    }

    .slider-item h3 {
        font-size: 24px;
        color: #00145B;
        margin-bottom: 10px;
    }

    .slider-item p {
        font-size:16px;
        color: #555;
        margin-bottom: 20px;
    }

    .slider-item img {
        width: 100%;
        height: auto;
        max-height: 200px;
        border-radius: 5px;
        margin-bottom: 10px;
    }

    .service-button {
        background-color: #2A65FF;
        color: #fff;
        border: none;
        border-radius: 5px;
        padding: 10px 20px;
        font-size: 16px;
        cursor: pointer;
        transition: background-color 0.3s;
    }

    .service-button:hover {
        background-color: #0043b2;
    }
`;
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();
    }
}
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();
    }
}
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());
        }
    }
}
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);
        }
    }
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class ListIteratorExample {
    public static void main(String[] args) {
        // Creating and populating an ArrayList
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Apple");
        arrayList.add("Banana");
        arrayList.add("Cherry");

        // Creating and populating a LinkedList
        List<String> linkedList = new LinkedList<>();
        linkedList.add("Dog");
        linkedList.add("Elephant");
        linkedList.add("Frog");

        // Iterating over the ArrayList
        System.out.println("Iterating over ArrayList:");
        Iterator<String> arrayListIterator = arrayList.iterator();
        while (arrayListIterator.hasNext()) {
            String item = arrayListIterator.next();
            System.out.println(item);
        }

        // Iterating over the LinkedList
        System.out.println("\nIterating over LinkedList:");
        Iterator<String> linkedListIterator = linkedList.iterator();
        while (linkedListIterator.hasNext()) {
            String item = linkedListIterator.next();
            System.out.println(item);
        }
    }
}
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);
    }
}
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);
    }
}
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);
   }
}
		
		
		
        
CREATE TABLE empc (
    emp_id NUMBER PRIMARY KEY,
    name VARCHAR2(100),
    hire_date DATE
    -- other columns
);
DECLARE
    CURSOR emp_cursor IS
        SELECT empno, ename, hiredate
        FROM employee
        WHERE (SYSDATE - hiredate) / 365.25 >= 23;  -- Calculate experience in years
    emp_record emp_cursor%ROWTYPE;
BEGIN
    OPEN emp_cursor;
    LOOP
        FETCH emp_cursor INTO emp_record;
        EXIT WHEN emp_cursor%NOTFOUND;
        
        INSERT INTO empc (emp_id, name, hire_date)
        VALUES (emp_record.empno, emp_record.ename, emp_record.hiredate);
    END LOOP;
    CLOSE emp_cursor;
    
    COMMIT;
END;
/
create or replace Trigger mytrigger 
before insert on employee
begin 
 dbms_output.put_line('Record inserted ');
end;
/
DECLARE
    v_department_id NUMBER := &department_id;  -- Accept department number as input
BEGIN
    FOR emp_record IN (
        SELECT empno, ename, hiredate, deptno
        FROM employee
        WHERE deptno= v_department_id
    )
    LOOP
        DBMS_OUTPUT.PUT_LINE('Emp ID: ' || emp_record.empno);
        DBMS_OUTPUT.PUT_LINE('Name: ' || emp_record.ename);
        DBMS_OUTPUT.PUT_LINE('Hire Date: ' || TO_CHAR(emp_record.hiredate, 'YYYY-MM-DD'));
        DBMS_OUTPUT.PUT_LINE('Department ID: ' || emp_record.deptno);
        DBMS_OUTPUT.PUT_LINE('-----------------------------');
    END LOOP;
END;
/
create or replace Trigger mytrigger2
after insert or update on employee
begin 
  case  
   when inserting then 
 dbms_output.put_line('Record  inserting');
  when updating then
    dbms_output.put_line('record updating');
  end case;
end;
/
declare 
a integer:=&a;
c integer:=0;
i integer;
begin
   
   for i in 1 .. a-1
   loop
      if (mod(a,i)=0) then
         c:=c+i;
     end if;
    end loop;
  if c=a 
then 
   dbms_output.put_line('Perfect number');
else
  dbms_output.put_line('Not Perfect number');
end if;
end;
/
     
 
declare
    cursor c1 is select * from employee;
   e employee%rowtype;
 begin
   open c1;
   loop
    fetch c1 into e;
   exit when c1%notfound;
   dbms_output.put_line(e.empno||'    ' ||e.ename||'    '||e.sal);
  end loop;
end;
/
   
declare 
    str varchar(2);
begin
   str:='sa';
   exception
      when value_error then
    dbms_output.put_line('invalid input');
 end;
/
create or replace Trigger mytrigger1 
after insert on employee
begin 
 dbms_output.put_line('Record inserted using after');
end;
/
declare
  cursor c1 is select * from employee;
  e employee%rowtype;
begin 
  open c1;
  loop
   fetch c1 into e;
      exit when c1%rowcount>5;
     dbms_output.put_line(e.empno||'     '||e.ename);
   end loop;
end;
/
DECLARE
    threshold_salary NUMBER := 1000; -- You can change this value as needed
BEGIN
    -- Using an implicit cursor to update the salary
    UPDATE employee
    SET sal = sal * 1.2
    WHERE sal > threshold_salary;

    -- Display the number of rows updated
    DBMS_OUTPUT.PUT_LINE(SQL%ROWCOUNT || ' rows updated.');
END;
/
declare
    neg exception;
    s employee.empno%type:=&empno;
begin
  if (s<0) then 
      raise neg;
   else 
       dbms_output.put_line('record inseted');
   end if;
 exception
   when neg then 
    dbms_output.put_line('negative number ');
end;
/
declare
cursor c1 is select * from employee;
e employee%rowtype;
begin
 close c1;
exception 
    when invalid_cursor then
      dbms_output.put_line('invalid cursor');
end;
/
declare 
a integer:=&a;
c integer:=0;
i integer;
begin
   
   for i in 1 .. a-1
   loop
      if (mod(a,i)=0) then
         c:=c+i;
     end if;
    end loop;
  if c=a 
then 
   dbms_output.put_line('Perfect number');
else
  dbms_output.put_line('Not Perfect number');
end if;
end;
/
     
 
create or replace procedure palind(ran in out integer,res in out integer)
Is
  num1 integer:=0;
  
   i integer;
 su integer:=ran;
begin 
   while (ran>0)
 loop
    i:=mod(ran,10);
    num1:=num1*10+i;
   ran:=trunc(ran/10); 
    end loop;
 if (su=num1) then
    res:=1;
else
   res:=0;
end if;
end;
/
declare 
  a integer:=&a;
  b integer:=0;
begin 
  palind(a,b);
   if (b=1) then 
   dbms_output.put_line(' Palindrome');
   else 
  dbms_output.put_line('Not Palindrome');
  end if;
end;
/
  
create or replace procedure swap( num1 in out integer,num2 in out integer)
Is 
 temp integer:=0;

begin 
    temp:=num1;
    num1:=num2;
    num2:=temp;  
end;
/
declare 
  a integer:=&a;
  b integer:=&b;
begin 
  dbms_output.put_line('Before swaping '||a||'  '||b);
  swap(a,b);
   dbms_output.put_line('After swaping '||a||'  '||b);

end;
/
  
DECLARE
    v_count NUMBER;
BEGIN
    -- Open implicit cursor
    SELECT COUNT(*)
    INTO v_count
    FROM employee;

    IF v_count > 0 THEN
        DBMS_OUTPUT.PUT_LINE('At least one row satisfies the condition::  '||v_count);
    ELSE
        DBMS_OUTPUT.PUT_LINE('No rows satisfy the condition.');
    END IF;
END;
/
create or replace procedure fibnoci(ran in out integer)
Is 
 temp integer:=0;
  num1 integer:=0;
  num2 integer:=1;
   i integer;
begin 
   dbms_output.put_line(num1);
  dbms_output.put_line(num2);
   for i in 1 .. (ran-2)
      loop
         
         temp:=num1+num2;
         num1:=num2;
         num2:=temp;
       dbms_output.put_line(temp);
         
    end loop;
end;
/
declare 
  a integer:=&a;
begin 
  fibnoci(a);
end;
/
  
Declare 
   a integer :=&a;
   i integer;
   
begin
  for i in 1 .. a
   loop
      if (mod(i,2)=0) then
         dbms_output.put_line('even '||i);
     -- else
     -- dbms_output.put_line('odd '||i);
    end if;
  end loop;
end;
/
DECLARE
    
    v_ename VARCHAR2(100);

    -- Implicit cursor
    CURSOR c_employee IS SELECT ename FROM employee; -- Replace your_table with the actual table name

BEGIN
    OPEN c_employee;

    -- Fetch and process each row
    LOOP
        -- Fetching data from the cursor into v_ename
        FETCH c_employee INTO v_ename;

         EXIT WHEN c_employee%NOTFOUND;

        -- Update the ename column to uppercase
        UPDATE employee SET ename = UPPER(v_ename);
    END LOOP;

    -- Close the cursor
    CLOSE c_employee;

    -- Output message
    DBMS_OUTPUT.PUT_LINE('All ename values updated to uppercase.');
END;
/
CREATE OR REPLACE FUNCTION power(x IN NUMBER, n IN NUMBER) RETURN NUMBER IS
  result NUMBER := 1; -- Variable to store the result
  i NUMBER := 0; -- Loop counter
BEGIN
        FOR i IN 1..n LOOP
      result := result * x;
    END LOOP;
    RETURN result;
END;
/

declare 
 a integer:=&a;
  b integer:=&b;
begin
    
  dbms_output.put_line('factorial :'||power(a,b));
end;
/
create or replace procedure revers(ran in out integer)
Is
  num1 integer:=0;
  
   i integer;
begin 
   while (ran>0)
 loop
    i:=mod(ran,10);
    num1:=num1*10+i;
   ran:=trunc(ran/10); 
    end loop;
  dbms_output.put_line('reversed  number  ::'|| num1);
end;
/
declare 
  a integer:=&a;
begin 
  revers(a);
end;
/
  
create or replace FUNCTION  gcd(num1 IN out NUMBER, num2 IN out NUMBER) return  NUMBER 
Is
  t NUMBER:=1;
BEGIN
	while (mod(num2, num1)!=0)
            loop
		t := mod(num2, num1); 

		num2 := num1; 

		num1 := t; 
	end loop; 

  return num1;  
  end;
/

DECLARE
  num1 NUMBER := 56;  -- First number
  num2 NUMBER := 98;  -- Second number
  gcd_result NUMBER;  -- Variable to store the result
BEGIN
    gcd_result := gcd(num1, num2);
  
  -- Output the result
  DBMS_OUTPUT.PUT_LINE('The GCD of ' || num1 || ' and ' || num2 || ' is ' || gcd_result);
END;
/
declare
    neg exception;
    s employee.empno%type:=&empno;
begin
  if (s<0) then 
      raise neg;
   else 
       dbms_output.put_line('record inseted');
   end if;
 exception
   when neg then 
    dbms_output.put_line('negative number ');
end;
/
declare 
a integer:=&a;
c integer:=a;
d integer;
sume integer:=0;
begin
   
     while (a>0)
   loop
         d:=mod(a,10);
         sume:=sume+d*d*d;
         a:=trunc(a/10);
    end loop;
  if (sume=c)
then 
   dbms_output.put_line('Amstrong number');
else
  dbms_output.put_line('Not Amstrong number');
end if;
end;
/
     
 
create or replace procedure fibnoci(ran in out integer)
Is 
 temp integer:=0;
  num1 integer:=0;
  num2 integer:=1;
   i integer;
begin 
   dbms_output.put_line(num1);
  dbms_output.put_line(num2);
   for i in 1 .. (ran-2)
      loop
         
         temp:=num1+num2;
         num1:=num2;
         num2:=temp;
       dbms_output.put_line(temp);
         
    end loop;
end;
/
declare 
  a integer:=&a;
begin 
  fibnoci(a);
end;
/
  
DECLARE
    v_count NUMBER;
BEGIN
    -- Open implicit cursor
    SELECT COUNT(*)
    INTO v_count
    FROM employee;

    IF v_count > 0 THEN
        DBMS_OUTPUT.PUT_LINE('At least one row satisfies the condition::  '||v_count);
    ELSE
        DBMS_OUTPUT.PUT_LINE('No rows satisfy the condition.');
    END IF;
END;
/
star

Mon May 27 2024 08:53:57 GMT+0000 (Coordinated Universal Time) https://www.kryptobees.com/axie-infinity-clone-script

@jackwyatt134 ##axieinfinityclonescript#metaversegame #virtualreality

star

Mon May 27 2024 08:34:18 GMT+0000 (Coordinated Universal Time)

@Shira

star

Mon May 27 2024 08:13:39 GMT+0000 (Coordinated Universal Time)

@davidmchale #while #loop

star

Mon May 27 2024 05:59:30 GMT+0000 (Coordinated Universal Time)

@ajjjuu

star

Mon May 27 2024 05:49:55 GMT+0000 (Coordinated Universal Time) https://laravel-livewire.com/docs/2.x/input-validation

@tsesang

star

Mon May 27 2024 05:03:18 GMT+0000 (Coordinated Universal Time) https://research.google.com/colaboratory/local-runtimes.html

@kris96tian

star

Mon May 27 2024 04:05:18 GMT+0000 (Coordinated Universal Time) https://laravel-livewire.com/docs/2.x/properties

@tsesang

star

Mon May 27 2024 04:04:51 GMT+0000 (Coordinated Universal Time) https://laravel-livewire.com/docs/2.x/properties

@tsesang

star

Mon May 27 2024 04:00:08 GMT+0000 (Coordinated Universal Time) https://laravel-livewire.com/docs/2.x/properties

@tsesang

star

Mon May 27 2024 03:58:04 GMT+0000 (Coordinated Universal Time) https://laravel-livewire.com/docs/2.x/properties

@tsesang

star

Mon May 27 2024 03:07:54 GMT+0000 (Coordinated Universal Time)

@davelauren #javascript #svelte

star

Mon May 27 2024 02:58:35 GMT+0000 (Coordinated Universal Time)

@signup

star

Mon May 27 2024 01:25:59 GMT+0000 (Coordinated Universal Time)

@allen_ #javascript

star

Mon May 27 2024 00:04:28 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Sun May 26 2024 21:20:49 GMT+0000 (Coordinated Universal Time)

@shirogan3x

star

Sun May 26 2024 20:57:03 GMT+0000 (Coordinated Universal Time)

@shirogan3x

star

Sun May 26 2024 20:29:21 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Sun May 26 2024 20:29:19 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Sun May 26 2024 20:27:14 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Sun May 26 2024 20:23:39 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Sun May 26 2024 20:22:40 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Sun May 26 2024 20:21:22 GMT+0000 (Coordinated Universal Time)

@prabhas

star

Sun May 26 2024 17:56:03 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:54:36 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:53:55 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:53:15 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:52:52 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:52:20 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:51:54 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:51:28 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:50:33 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:50:02 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:49:34 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:49:12 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:48:02 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:47:37 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:47:10 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:46:48 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:46:44 GMT+0000 (Coordinated Universal Time)

@signup

star

Sun May 26 2024 17:46:19 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:45:54 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:45:31 GMT+0000 (Coordinated Universal Time)

@signup

star

Sun May 26 2024 17:45:28 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:44:59 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:44:53 GMT+0000 (Coordinated Universal Time)

@signup

star

Sun May 26 2024 17:44:35 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:44:10 GMT+0000 (Coordinated Universal Time)

@exam123

star

Sun May 26 2024 17:43:44 GMT+0000 (Coordinated Universal Time)

@signup

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension