Day04 datetime Lambda expression

Day04 datetime Lambda expression

Date and time

Overview of data class

The Date object represents the current Date and time of the current system in the return va.

Constructor for Date

name explain
public Date() Create a Date object to represent the current Date and time of the system.

Common methods of Date

name explain
public long getTime() Gets the millisecond value of the time object

The Date class records two forms of time

Form 1: Date object

//1. create an object of date class to represent the current time and Date object of the system
Date d = new Date();
System.out.println(d);

Form 2: time millisecond value

It refers to the total number of milliseconds from January 1, 1970, 00:00:00 to the present. It should be very large
    long time = d.getTime();
	System.out.println(time);

Case:

Please calculate the time after 1 hour and 121 seconds from the current time

Time millisecond value - > Date object

constructor explain
public Date(long time) Convert time millisecond value to date Date object
Date method explain
public void setTime(long time) Set the time of the date object to the time corresponding to the current time millisecond value
public class DateDemo01 {
    public static void main(String[] args) {
        //1. create an object of date class to represent the current time and Date object of the system
        Date d = new Date();
        System.out.println(d);

        //2. get the current time in milliseconds
        long time = d.getTime();
        System.out.println(time);
        System.out.println("---------------");
        long time1 = System.currentTimeMillis();
        System.out.println(time1);

        System.out.println("-----------");
        //1. millisecond value of current time
        Date d1 = new Date();
        System.out.println(d1);

        //2. go back 1 hour 121s from the current time
        long time2 = System.currentTimeMillis();
        time2 += (60 * 60 + 121) * 1000;

        //3. convert the time millisecond value to the corresponding date object
        Date d2 = new Date(time2);
        System.out.println(d2);

        //4. another method
        Date d3 = new Date();
        d3.setTime(time2);
        System.out.println(d3);
    }
}

! [image-20220425123841397](Day04 date time Lambda expression.assets/image-20220425123841397.png)

The role of the SimpleDateFormat class

You can format the Date object or the time millisecond value into our preferred time form

You can also parse the time form of a string into a date object

! [image-20220425124418189](Day04 date time Lambda expression.assets/image-20220425124418189.png)

Constructor for SimpleDateFormat

constructor explain
SimpleDateFormat() Construct a SimpleDateFormat using the default format
SimpleDateFormat(String pattern) Construct a SimpleDateFormat using the specified format

Formatting method for SimpleDateFormat

formatting method explain
public final String format(Date date) Format date as date / time string
public final String format(Object time) Converts the time millisecond value to a date / time string

The common patterns for formatting time forms correspond to the following

! [image-20220425141959609](Day04 date time Lambda expression.assets/image-20220425141959609.png)

public class SimpleDateFormatDemo01 {
    public static void main(String[] args) {
        //1. Date object
        Date d = new Date();
        System.out.println(d);

        //2. format this date object (specify the final format)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd EEE HH:mm:ss a");

        //3. start formatting date objects into preferred string form
        String rs = sdf.format(d);
        System.out.println(rs);
    }
}

SimpleDateFormat parses string time into datetime

analytic method explain
public Date parse(String source) Parses text from the start of a given string to generate time

Case:

Please calculate the time after 11:11:11 on August 6, 2021 and 2 days later, 14 hours, 49:06 seconds?

public class SimpleDateFormatDemo02 {
    public static void main(String[] args) throws ParseException {
        System.out.println("----Parsing string time----");
        //Please calculate the time after 11:11:11 on August 6, 2021 and 2 days later, 14 hours, 49:06 seconds?

        //1. get the string time into the program
        String time = "2021 August 6, 2011 11:11:11";

        //2. parse string time into time object
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
        Date d = sdf.parse(time);

        //3. go back for 2 days, 14 hours, 49 minutes and 06 seconds
        long time1 = d.getTime() + (2 * 24 * 60 * 60 + 14 * 60 * 60 + 49 * 60 + 6) * 1000;
        
        //4. format this time millisecond value to be the result
        System.out.println(time);
        String rs = sdf.format(time1);
        System.out.println(rs);
    }
}
summary
//1. What time forms can SimleDateFormat format format?
SimpIeDateFormat sdf = new Simp1eDateFormat("yyyy-MM-dd HH: mm: ss);
String rsl = sdf.format(date);
String rs2 = sdf.format(time);

//2. How does SimpleDateFormat parse string time?
Simp1eDateFormat sdf = new SimpIeDateFormat"yyyy-MM-dd HH: mm: ss);
Date d = sdf.parse(("2021-08-04 11:11:11) ;

Calendar overview (calendar)

  • Calendar represents the calendar object corresponding to the current date of the system

  • Calendar is an abstract class and cannot create objects directly

Method of Calendar class to create Calendar object: (drop method)

public static Calendar getInstance()  ->Get current calendar object
    Calendar cal = Calendar.getInstance();

Calendar common methods:

Method name explain
public int get(int field) Get the information of a field in the date.
public void set(int field,int value) Modify a field information of the calendar.
public void add(int field, int amount) Increase / decrease the specified value for a field
public final Date getTime() Get the current date object.
public long getTimeInMillis() Get the current time in milliseconds

calendar is a variable Date object. Once modified, the time represented by the object itself will change.

JDK8 add date class

Overview: LocalTime, LocalDate, LocalDateTime

! [image-20220425185124469](Day04 date time Lambda expression.assets/image-20220425185124469.png)

! [image-20220425185142273](Day04 date time Lambda expression.assets/image-20220425185142273.png)

! [image-20220425192838046](Day04 date time Lambda expression.assets/image-20220425192838046.png)
! [image-20220425193130631](Day04 date time Lambda expression.assets/image-20220425193130631.png)

Instant timestamp

! [image-20220425195104903](Day04 date time Lambda expression.assets/image-20220425195104903.png)

DateTimeFormatter:

! [image-202204251953748] (day04 date time Lambda expression.assets/image-20220425195953748.png)

Duration/Period

Period:

! [image-20220425201138267](Day04 date time Lambda expression.assets/image-20220425201138267.png)

Duration:

! [image-20220425201503136](Day04 date time Lambda expression.assets/image-20220425201503136.png)

Chrononunit: used to measure a period of time in a single time unit

//Local date time object
LocalDateTime today = LocalDateTime.now();
System.out.println(today);

//Date of birth object
LocalDateTime birTime = LocalDateTime.of(1999, 11, 13, 05, 22,50);
System.out.println(birTime);

System.out.println("Years of difference:" + ChronoUnit.YEARS.between(birTime,today));
System.out.println("Months of difference:" + ChronoUnit.MONTHS.between(birTime,today));
System.out.println("Weeks of difference:" + ChronoUnit.WEEKS.between(birTime,today));
System.out.println("Days difference:" + ChronoUnit.DAYS.between(birTime,today));
System.out.println("Hours of difference:" + ChronoUnit.HOURS.between(birTime,today));
System.out.println("Difference score:" + ChronoUnit.MINUTES.between(birTime,today));
System.out.println("Seconds difference:" + ChronoUnit.SECONDS.between(birTime,today));
System.out.println("Milliseconds difference:" + ChronoUnit.MILLIS.between(birTime,today));
System.out.println("Microseconds of difference:" + ChronoUnit.MICROS.between(birTime,today));
System.out.println("Nanoseconds of difference:" + ChronoUnit.NANOS.between(birTime,today));
System.out.println("Half day difference:" + ChronoUnit.HALF_DAYS.between(birTime,today));
System.out.println("Difference of half a day and ten years:" + ChronoUnit.DECADES.between(birTime,today));
System.out.println("Half day century (hundred years) difference:" + ChronoUnit.CENTURIES.between(birTime,today));

Packaging:

In fact, it is the reference data type corresponding to the basic data type in 8

Basic data type Reference data type
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
boolean Boolean

Why packaging is provided:

  • In order to realize "everything is an object", java provides corresponding reference types for eight basic types

  • Later collections and generics can only support wrapper types

Auto packing: data and variables of basic type can be directly assigned to variables of packing type.

int a = 10;
Integer a2 = a;//Automatic packing

Automatic unpacking: variables of package type can be directly assigned to variables of basic data type.

Integer it = 100;
int it1 = it;//Automatic unpacking

Unique functions of packaging

  • The default value of the variables of the wrapper class can be null, with a higher fault tolerance rate

int age = null;//Error will be reported
Integer age1 = null;//Yes
  • Can convert basic type data to string type (not very useful)

  • Call the tostring() method to get the string result.
  • Call lnteger ToString (data of basic type).

You can convert numeric values of string type to real data types (really useful)

  • lnteger.parselnt("integer of string type")
  • Double.parseDouble("decimal of string type").
  • Use double/integer Valueof (string s) can achieve the same effect

! [image-20220426130043046](Day04 date time Lambda expression.assets/image-20220426130043046.png)

Regular expression:

Regular representation:

Regular expressions can use some specified characters to formulate rules and verify the validity of the data format

! [image-20220426143327543](Day04 date time Lambda expression.assets/image-20220426143327543.png)

Which method of the String class can match a regular expression

public boolean matches(String regex);
//Judge whether the regular expression is matched. If it is matched, it returns true. If it is not matched, it returns false

Application of regular expression in string method

Method name explain
public String replaceAll(String regex,String newStr) Replace by regular expression matching
public String[] split(String regex) Divide the string according to the contents matched by the regular expression, and return an array of strings

Regular expression crawling information

public class RegexDemo05 {
    public static void main(String[] args) {
        String rs = "Come to DIU to study geological engineering, Tel. 100-120119,Or contact email" +
                "1202120421@cug.com,Tel: 15072179532027-5715330" +
                "P.O. Box 21312312113@qq.com,Tel: 15827290767";

        //Demand, crawl from the above content to get the phone number and mailbox
        //1. define crawling rules
        String regex = "(\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z0-9]" +
                "{2,20}){1,2}|(1[3-9]\\d{9})" + "|(0\\d{2,6}-?\\d{5,20})" +
                "|(400-?\\d{3,9}-?\\d{3,9}))";

        //2. compile the crawled data into matching objects
        Pattern pattern = Pattern.compile(regex);

        //3. get a content matcher object
        Matcher matcher = pattern.matcher(rs);

        //4. start looking
        while (matcher.find()){
            String rs1 = matcher.group();
            System.out.println(rs1);
        }
    }
}
1202120421@cug.com
15072179532
027-5715330
21312321213@qq.com
15827290767

Arrays class

Overview of the Arrays class

Array manipulation tool class, which is specially used to manipulate array elements

Common API s for the Arrays class

Method name explain
Public static string toString (type [] a) Sort array
Public static void sort (type [] a) Default ascending sort of array
Public static void sort (type [] A, comparator <? Super t>c) Customize sorting with comparer objects
public static int bbinarySearch(int[] a,int key) Data in binary search array. If there is a return index, if there is no return -1

Custom collation

Set the Comparator object corresponding to the Comparator interface to customize the comparison rules

! [image-20220426160804837](Day04 date time Lambda expression.assets/image-20220426160804837.png)

Common algorithms

Idea of selective sorting

Select the current position every round, and start to find the smaller value to exchange with this position

Select the key for sorting

Determine the total number of rounds to be selected: the length of the array is -1;

Control each round from the previous position as the benchmark, and select the following elements several times

Binary search

The binary search has good performance. The premise of binary search is that the data must be sorted well

Binary search is equivalent to removing half of the data each time

Binary search -- element does not exist:

  • Conclusion: the normal search condition for binary search should be the starting position min < = the ending position max

Implementation steps:

Lambda expression

Lambad overview:

The.Lambda expression is a new syntax form after the beginning of EJDK 8.

Function: simplify the code writing of anonymous inner classes.

Simplified format of Lambda expression

(List of formal parameters of overridden methods of anonymous inner classes)-> {
Method body code of the overridden method.
}
Note: -> Is a grammatical form/ No actual meaning

Lambda expressions can only simplify the writing of anonymous inner classes of functional interfaces.

What is a functional interface

  • First, it must be an interface. Second, there must be only one abstract method in the interface

  • Usually, we will add a @FunctionalInterface annotation on the interface, marking that the interface must be the interface that satisfies the function

summary~
//1. What are the basic functions of Lambda expressions?
. Simplifies the writing of anonymous inner classes for functional interfaces.
//2. What are the prerequisites for Lambda expressions?
. Must be an anonymous inner class of an interface. There can only be one abstract method in an interface
//3. Lambda benefits?
. Lambda Is an anonymous function, we can Lambda The expression is understood as
 It is a piece of code that can be passed. It can write more concise and flexible code,
As a more compact code style, java Language skills have been improved.

Omission of Lambda expression (further simplification on the basis of Lambda expression)

. the number type can be omitted.

. if there is only one parameter, the parameter type can be omitted, and 0 can also be omitted.

. if the method body code of a Lambda expression has only one line of code. You can omit the braces and omit the semicolon!

. if the method body code of a Lambda expression has only one line of code. Braces can be omitted. At this point, if this line of code is a return statement, return must be omitted and must also be omitted; Do not write

public class LambdaDemo02 {
    //Lambda expressions can only simplify the writing of anonymous inner classes of functional interfaces.
    public static void main(String[] args) {
        /*Swimming s1 = new Swimming(){
            @Override
            public void Swim() {
                System.out.println("The teacher swims fast! ");
            }
        };
        go(s1);*/
        Swimming s1 = () ->{
            System.out.println("The teacher swims slowly~");
        };
        Swimming s2 = () -> System.out.println("The teacher swims slowly~");
        go(s1);

        System.out.println("-----------");
       /* go(new Swimming() {
            @Override
            public void Swim() {
                System.out.println("Students are good at it 🏊 ‍");
            }
        });*/
        go(() ->{
            System.out.println("Students are good at it🏊‍");
        });
        go(() -> System.out.println("Students are good at it🏊‍"));
    }

    public static void go(Swimming s){
        System.out.println("start~");
        s.Swim();
        System.out.println("end~");
    }
}

@FunctionalInterface//Mark that the interface must be the interface that satisfies the function. There is only one abstract method in the interface
interface Swimming{
    void Swim();

Posted by lizard on Wed, 01 Jun 2022 21:36:02 +0530