vasanth0989 / prep-myself

0 stars 0 forks source link

Generics and Collections #4

Open vasanth0989 opened 10 months ago

vasanth0989 commented 10 months ago
package com.test;

import java.util.ArrayList;
import java.util.List;

public class TestMain {

    public static void main(String[] args) {
        //old school for loop
        // for each loop (Java 1.5)
        Employee emp1 = new Employee("John", 25);
        Employee emp2 = new Employee("Smith", 32);

        List<Employee> employees = new ArrayList<>();
        employees.add(emp1); //0
        employees.add(emp2); //1

        System.out.println("size:"+employees.size());
//        System.out.println("Employee 0 Name:"+employees.get(0).getName());
//        System.out.println("Employee 1 Name:"+employees.get(1).getName());

        for(int i=0; i < employees.size();i++){
            System.out.println("Employee "+ i +" Name:"+employees.get(i).getName());
        }

        //Enhanced for loop 1.5 for each loop
        for(Employee emp: employees){
            System.out.println("Employee Name:"+emp.getName());
        }

//        printWithForLoop(employees);

        Shape circle = new Circle();
        printInstance(circle);
        Square square = new Square();

        // List
        List list = new ArrayList();
        double xd = 25.35;
        long xl = 2424242;
        int xi = 242;
        String xs = "Vasanth";
        list.add(xd);
        list.add(xl);
        list.add(xs);

        //Generics <>
        List<String> strList = new ArrayList<>();
        strList.add(xs);

    }

    static void printWithForLoop(List<Employee> employees){
      for(int i=0; i < employees.size(); i++){

      }

    }

    static void printInstance(Shape x) {
        if (x instanceof Circle) {
            System.out.println("This is a circle object");
            x.draw();
            Circle circle = (Circle) x;
            circle.getArea();
        } else if (x instanceof Square) {
            x.draw();
            Square square = (Square) x;
            System.out.println("This is a Square");
        }
    }
}

class Employee {
    private String name;
    private int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
vasanth0989 commented 10 months ago
public interface Shape {

    // Method definition
    // No method implementation
    void draw();
}
public class Circle  implements Shape{
    @Override
    public void draw() {
        System.out.println("I am drawing Circle");
    }

    void getArea(){
        System.out.println("Calculating area");
    }
}
public class Square implements Shape{
    @Override
    public void draw() {
        System.out.println("I am drawing Square");
    }
}
vasanth0989 commented 10 months ago
Collections:
    List:
     - ArrayList
     - LinkedList
     - Stack
     - Queue
    Set:
     - HashSet
     - LinkedHashSet
    Map:
     - HashMap
     - LinkedHashMap

Java is platform independent language:

Employee.java - Human readable - Source code

compilation -> .java -> .class file

JVM: - Java Virtual Machine -> .class file (bytes) Running on top your Operating System

vasanth0989 commented 10 months ago

This is to cover Set, and Map

import java.util.*;

public class LearningException {

    public static void main(String[] args) {
        // Example for Null Pointer Exception (Unchecked / RunTimeException)
        Employee employee = new Employee(123, "Test");
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(123, "Test01"));
        employees.add(new Employee(456, "Test02"));
        // Printing employees using forEach
//        for(Employee emp: employees){
//            System.out.println(emp);
//        }

        // List with duplicates, to prove that list can contain duplicates

        List<String> fruits = new ArrayList<>();
        fruits.add("apple");
        fruits.add("mango");
        fruits.add("apple");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        // You Access list with index value
        System.out.println("First element" + fruits.get(2));
        System.out.println("Set begins..");
        // Set, this is avoid duplicates
        // Hashset will not maintain insertion order
        Set<String> fruitsSet = new HashSet<>();
        fruitsSet.add("apple");
        fruitsSet.add("mango");
        fruitsSet.add("apple");
        for (String fruit : fruitsSet) {
            System.out.println(fruit);
        }
        // Handy constructor available in HashSet where you can pass in the List
        // Remove duplicates from List
        System.out.println("****");
        Set<String> setWithoutDuplicate = new HashSet<>(fruits);
        for (String fruit : setWithoutDuplicate) {
            System.out.println(fruit);
        }
        // LinkedHashSet
        // It will maintain the insertion order
        System.out.println("*****");
        Set<String> fruitsLinkedHashSet = new LinkedHashSet<>();
        fruitsLinkedHashSet.add("apple");
        fruitsLinkedHashSet.add("mango");
        fruitsLinkedHashSet.add("apple");
        for (String fruit : fruitsLinkedHashSet) {
            System.out.println(fruit);
        }

        // Map
        // You can use it for Key, Value pair
        // HashMap will not maintain the insertion order
        Map<String, Integer> employeeCountMap = new HashMap<>();
        employeeCountMap.put("Discover", 10_000);
        employeeCountMap.put("Chase", 20_000);

        // You can always retrieve the value by its key
        System.out.println("Employee count for Discover: " + employeeCountMap.get("Discover"));
        System.out.println("Employee count for Chase: " + employeeCountMap.get("Chase"));

        // print only the keys
        System.out.println("Printing the keys");
        for (String key : employeeCountMap.keySet()) {
            System.out.println(key);
        }
        // print only the values
        System.out.println("Printing the values");
        for (Integer value : employeeCountMap.values()) {
            System.out.println(value);
        }

        // printing both the key and the value using Map.Entry
        System.out.println("Printing the Entry set that contains both key and value");
        for (Map.Entry<String, Integer> entry : employeeCountMap.entrySet()) {
            System.out.println("Key: " + entry.getKey() + " value: " + entry.getValue());
        }

        // Utility that will be returning a boolean
        // we can check whether the map contains the particular key
        if (employeeCountMap.containsKey("Google")) {
            System.out.println("Key found!");
        } else {
            System.out.println("Key not found!");
        }

        // LinkedHashMap
        // This is exactly same as HashMap, the benefit is gonna is the insertion order will be maintained.
        Map<String, Integer> employeeCountLinkedHashMap = new LinkedHashMap<>();
        employeeCountLinkedHashMap.put("Discover", 10_000);
        employeeCountLinkedHashMap.put("Chase", 20_000);

    }
}

class Employee {
    private int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public Employee() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
vasanth0989 commented 10 months ago

Problem Grouping Accounts by its type

public class LearningException {

    public static void main(String[] args) {

        // declaring variable as final, you cannot reassign it.
        final String name = "vasanth";
        // the below line will result in an error
        //name = "Teja";

        List<Account> accounts = new ArrayList<>();
        accounts.add(new Account(1, "CHK"));
        accounts.add(new Account(2, "SVG"));
        accounts.add(new Account(3, "CHK"));
        accounts.add(new Account(4, "SVG"));

        //Problem: Group the accounts by its type
        // CHK -> 1, 3; SVG -> 2,4
        Map<String, List<Account>> accountMp = new HashMap<>();
        // Steps has to be followed
        // 1. Check whether the particular key exists in the map - containsKey()
        // 2. If it contains the key we get the value -> which is going to return a List
        // 3. We will add this account to the list
        // 4. If the key doesn't exist we will adding the new key using put method
        // 5. As we are creating the new key, we have to create new ArrayList so that it is going to hold the new value
        for (Account account : accounts) {
            // meaning the map does not contain the key
            if (!accountMp.containsKey(account.getType())) {
                List<Account> accts = new ArrayList<>();
                accts.add(account);
                accountMp.put(account.getType(), accts);
            }
            // the key already exists, which means we would have already created the key
            // we just need get the value and add it to the list
            else {
                List<Account> existingAccts = accountMp.get(account.getType());
                existingAccts.add(account);
            }
        }
        System.out.println(accountMp);

    }
}

class Account {
    private int id;
    private String type;

    public Account() {
    }

    public Account(int id, String type) {
        this.id = id;
        this.type = type;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", type='" + type + '\'' +
                '}';
    }
}