Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
13 kB
3
Indexable
Never
javacore.organization

1. functionalprogramming
    1.1. function
        1.1.1. lambda
            1.1.1.1. Demo

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.function.Consumer;
/*
 * Bieu thuc Lambda la mot khoi ma nguon, co the co tham so dau vao va tra lai ket qua
 * Lambda khong can ten va co the cai dat ngay trong phuong thuc
 */

public class Demo {
	public static void main(String[] args) {
		ArrayList<Integer> numbers = new ArrayList<Integer>();
		numbers.add(1);
		numbers.add(3);
		numbers.add(20);
		numbers.forEach((n) ->{System.out.print(n + " ");});
		System.out.println();
		
		LinkedList<String> stringArr = new LinkedList<String>();
		stringArr.add("dog");
		stringArr.add("cat");
		stringArr.add("rabit");
		//khi chi co 1 cau lenh thi co the viet nhu duoi
		stringArr.forEach(n-> System.out.print(n + " "));
		System.out.println();
		
		//hoac viet ngan hon
		Consumer<Integer> method = System.out::println;
		numbers.forEach(method);
	}
}

###############################

            1.1.1.2. Main.java

import java.util.*;

public class Main {
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Printing from the Runnable");
            }
        }).start();

        new Thread(() -> System.out.println("This is a lambda expression")).start();

        Employee john = new Employee("John Doe", 30);
        Employee tim = new Employee("Tim Buchalka", 50);
        Employee jack = new Employee("Jack Hill", 40);
        Employee snow = new Employee("Snow White", 25);

        List<Employee> employees = new ArrayList<>(Arrays.asList(john, tim, jack, snow));

//        Collections.sort(employees, new Comparator<Employee>() {
//            @Override
//            public int compare(Employee employee1, Employee employee2) {
//                return employee1.getName().compareTo(employee2.getName());
//            }
//        });

        Collections.sort(employees, (employee1, employee2) -> employee1.getName().compareTo(employee2.getName()));

//        Collections.sort(employees, Comparator.comparing(Employee::getName));

        for (Employee employee : employees) {
            System.out.println(employee.getName() + " - " + employee.getAge());
        }

        String sillyString = doStringStuff((s1, s2) -> s1.toUpperCase() + " - " + s2.toUpperCase(),
                                           employees.get(0).getName(), employees.get(1).getName());
        System.out.println(sillyString);

        AnotherClass anotherClass = new AnotherClass();
        String s = anotherClass.doSomething();
        System.out.println(s);
    }

    public final static String doStringStuff(UpperConcat uc, String s1, String s2) {
        return uc.upperAndConcat(s1, s2);
    }
}

class AnotherClass {

    public String doSomething() {
        UpperConcat uc =  (s1, s2) -> {
            System.out.println("The lambda expression class's name is: " + getClass().getSimpleName());
            String result = s1.toUpperCase() + " - " + s2.toUpperCase();
            return result;
        };


        UpperConcat uc1 = new UpperConcat() {
            @Override
            public String upperAndConcat(String s1, String s2) {
                return s1.toUpperCase() + " - " + s2.toUpperCase();
            }
        };

        System.out.println("The AnotherClass class's name is: " + getClass().getSimpleName());

        return Main.doStringStuff(uc, "String1", "String2");

    }
}

interface UpperConcat {
    String upperAndConcat(String s1, String s2);
}

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;
    }
}

class CodeToRun implements Runnable{

    @Override
    public void run() {
        System.out.println("Printing from Runnable");
    }
}

###############################

            1.1.1.3. Solution.java

public class Solution {
	public interface StringFunction{
		String run(String str);
	}
	public static void printFormatted(String str, StringFunction format){
		String result = format.run(str);
		System.out.println(result);
	}
	public static void main(String[] args) {
		StringFunction exclaim = (s) -> s + "!!!";
		StringFunction as = (s) -> s + "???";
		printFormatted("Hello", exclaim);
		printFormatted("What", as);
	}
}

##############################

        1.1.2. methodreference
            1.1.2.1. Main.java

/*
 * Method reference cho phep truy cap truc tiep toi cac constructor hoac method cua lop hoac doi tuong
 * Cu phap: Object :: methodName
 */

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class Main {

    public static void main(String[] args) {

        Consumer<String> c = s -> System.out.println(s);
        Consumer<String> methodReference = System.out::println;

        List<String> list = Arrays.asList("Thieu", "Hien");
        list.forEach(methodReference);

        MyClass myClass = new MyClass();
        list.forEach(myClass::say);

        list.forEach(Test::say);
    }
}

class MyClass {

    private String str = "Unknown";

    public void say(String s) {
        System.out.println(str + " " + s);
    }
}

class Test {

    private static String str = "Hello";

    public static void say(String s) {
        System.out.println(str + " " + s);
    }
}

#######################################

    1.2. functionalstream
        1.2.1. stream
            1.2.1.1. Main.java

/*
 * input stream: doc data tu source
 * output stream: ghi data vao dich den
 *
 * stream co the chia thanh hai loai dua vao cach chung dai dien cho du lieu:
 * byte streams: doc va ghi du lieu theo byte -> co the hoat dong voi bat ky data loai nao (ke ca multimedia)
 * char streams: doc va ghi du lieu duoi dang ki tu theo dinh dang Unicode 16 bit
 *
 * mot vai stream su dung vi tri bo nho tam thoi (temporary memory location) -> thuong la mot mang byte hoac char
 * duoc goi la buffer
 * buffer cho phep doc luong lon du lieu tu data source va luu vao bo nho tam -> giam so lan  truy cap vao data source
 * (Giam so lan hoat dong I/O)
 */

public class Main {
    public static void main(String[] args) {
        MyClass myClass = new MyClass();

        MyClass.method2();
    }
}

class MyClass {

    static int field = 10;

    public MyClass() {
        method3(); // (1)
    }

    void method1() {
        method2(); // (2)
    }

    static void method2() {
        MyClass myClass = new MyClass();
        myClass.method3(); // (3)
    }

    void method3() {
        System.out.println(field); // (4)
    }
}

###############################################

2. genericprogramming
    2.1. essentials
    2.2. internals
    2.3. old
        2.3.1. BaseballPlayer
            
public class BaseballPlayer extends Player{
    public BaseballPlayer(String name) {
        super(name);
    }
}

###############################################

        2.3.2.FootballPlayer

public class FootballPlayer extends Player{
    public FootballPlayer(String name) {
        super(name);
    }
}

################################################

        2.3.3. Generics

import java.util.ArrayList;
import java.util.Arrays;

public class Generics {

    public static void main(String[] args) {
        // genericsIntroduce();
        myGenerics();
    }

    public static void myGenerics() {
        FootballPlayer joe = new FootballPlayer("Joe");
        BaseballPlayer pat = new BaseballPlayer("Pat");
        SoccerPlayer beckham = new SoccerPlayer("Beckham");

        Team<FootballPlayer> adelaideCrows = new Team<>("Adelaide Crows");
        adelaideCrows.addPlayer(joe);
        System.out.println(adelaideCrows.numPlayers());

        Team<BaseballPlayer> baseballTeam = new Team<>("Chicago Cubs");
        baseballTeam.addPlayer(pat);

        Team<SoccerPlayer> brokenTeam = new Team<>("This won't work");
        brokenTeam.addPlayer(beckham);

        Team<FootballPlayer> melbourne = new Team<>("Melbourne");
        FootballPlayer banks = new FootballPlayer("Gordon");
        melbourne.addPlayer(banks);

        Team<FootballPlayer> hawthorn = new Team<>("Hawthorn");
        Team<FootballPlayer> fremantle = new Team<>("Fremantle");

        hawthorn.matchResult(fremantle, 1, 0);
        hawthorn.matchResult(adelaideCrows, 3, 8);

        adelaideCrows.matchResult(fremantle, 2, 1);

        System.out.println("Ranking");
        System.out.println(adelaideCrows.getName() + ": " + adelaideCrows.ranking());
        System.out.println(melbourne.getName() + ": " + melbourne.ranking());
        System.out.println(fremantle.getName() + ": " + fremantle.ranking());
        System.out.println(hawthorn.getName() + ": " + hawthorn.ranking());

        System.out.println(adelaideCrows.compareTo(melbourne));
        System.out.println(adelaideCrows.compareTo(hawthorn));
        System.out.println(hawthorn.compareTo(adelaideCrows));
        System.out.println(melbourne.compareTo(fremantle));

    }

    public static void genericsIntroduce() {
        // raw type
        ArrayList items = new ArrayList();
        items.add(1);
        items.add(2);
        items.add(3);
        items.add(4);
        items.add(5);
        items.add(2.5);

        // generic
        ArrayList<Integer> newItems = new ArrayList<>(Arrays.asList(6, 7, 8, 9, 10));

        printDoubled(newItems);
    }

    private static void printDoubled(ArrayList<Integer> arr) {
        for (Integer i : arr) {
            System.out.println(i * 2);
        }
    }
}

####################################################

        2.3.4. Player

public abstract class Player {
    private String name;

    public Player(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

###############################################

        2.3.5. SoccerPlayer

public class SoccerPlayer extends Player{
    public SoccerPlayer(String name) {
        super(name);
    }
}

###########################################

        2.3.6. Team

public class Team<T extends  Player> implements Comparable<Team<T>>{
    private String name;
    int played = 0;
    int won = 0;
    int lose = 0;
    int tied = 0;
    private ArrayList<T> members = new ArrayList<>();

    public Team(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public boolean addPlayer(T player) {
        if (members.contains(player)) {
            System.out.println(player.getName() + " is already on this team.");
            return false;
        } else {
            members.add(player);
            System.out.println(player.getName() + " picked for team " + this.name);
            return true;
        }
    }

    public int numPlayers() {
        return this.members.size();
    }

    public void matchResult(Team<T> opponent, int outScore, int theirScore) {
        String message;
        if (outScore > theirScore) {
            won++;
            message = " beat ";
        } else if (outScore == theirScore) {
            tied++;
            message = " drew with ";
        } else {
            lose++;
            message = " lost to ";
        }
        played++;
        if (opponent != null) {
            System.out.println(this.getName() + message + opponent.getName());
            opponent.matchResult(null, theirScore, outScore);
        }
    }

    public int ranking() {
        return (won * 2) + tied;
    }

    @Override
    public int compareTo(Team<T> o) {
        return Integer.compare(this.ranking(), o.ranking());
    }
}

###########################################

3. method
    3.1. Overloading

public class Overloading {
	static void myMethod(String iName){
		// static -> phuong thuc nay thuoc Main va khong phai mot doi tuong cua Main
		System.out.println("Hello "+ iName);
	}
	
	//Method Overloading
	static int plusMethod(int x, int y){
		return x + y;
	}
	
	static double plusMethod(double x, double y){
		return x + y;
	}
	
	public static void main(String[] args) {
		myMethod("Thieu");

		System.out.println(plusMethod(2,1));
		System.out.println(plusMethod(2.1, 1.8));

		Overloading.myMethod("Han");
	}
}

Leave a Comment