Java8 full interpretation of two

Source: Internet
Author: User
Tags time zones stream api string format time and date

Continue with the last Java full interpretation of a

Continue with the last Java full interpretation of a
1. Powerful Stream API
1.1 What is stream
Three steps to 1.2 stream operation
1.2.1 Creating a Stream
Intermediate operation of the 1.2.2 stream
Filtering and slicing
Mapping
Sort
1.2.3 Stream's abort operation
Find and Match
Return to about
Collect
2 New Time Date API
2.1 Using Localdate, LocalTime, LocalDateTime
2.2 Duration and Period
2.3 Parsing and formatting
2.4 Time zone processing
The default method and static method in the 3 interface
Default method in the 3.1 interface
3.1.1 Use of default methods
The "class first" principle of the default method for 3.1.2 interfaces
Interface violation for the default method of the 3.1.3 interface
Static methods in the 3.2 interface

1. Powerful Stream API

Stream is a key abstraction for working with collections in Java8, which can specify what you want to do with collections, and can perform very complex operations such as finding, filtering, and mapping data. Using the stream API to manipulate collection data is similar to a database query executed using SQL. You can also use the stream API to perform operations in parallel. In short, the Stream API provides an efficient and easy-to-use way to process data.

1.1 What is stream

A stream is a data channel that is used to manipulate the sequence of elements generated by a data source (collection, array, and so on).

"The collection is about the data, and the flow is about computing!" ”

Note:
①stream itself does not store elements.
②stream does not change the source object. Instead, they return a new stream that holds the result.
The ③stream operation is deferred. This means that they will wait until the result is needed to execute.

Three steps to 1.2 stream operation
    • Create stream
      A data source (for example, a collection, an array), gets a stream
    • Intermediate operation
      An intermediate chain of operations to process data from a data source
    • Terminate operation (Terminal action)
      A terminating operation, performing an intermediate operation chain, and producing the result

1.2.1 Creating a Stream

There are three ways to create a stream in strict terms

    • The Collection interface in JAVA8 is extended to provide two ways to get the stream:
//Collection的方法default Stream<E> stream() : 返回一个顺序流default Stream<E> parallelStream() : 返回一个并行流
    • The static method of Arrays in Java8 stream () can get the array stream:
    • You can use the static method Stream.of ()to create a stream by displaying the value. It can receive any number of parameters
//Arrays的方法static <T> Stream<T> stream(T[] array);// 返回一个流//Stream的方法public static<T> Stream<T> of(T… values);// 返回一个流
    • You can use static methods Stream.iterate () and stream.generate ()to create an infinite stream.
//迭代public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)//生成public static<T> Stream<T> generate(Supplier<T> s) :/**UnaryOperator是传入类型T返回类型T* Supplier是无参,返回类型T*/

Practical use

public void test1(){        /**        * list中的数据本来是用List包裹,创建stream后,将list中的数据换成了stream包裹了,        * 同时对流中的数据操作变得更加方便        */        //1. Collection 提供了两个方法  stream() 与 parallelStream()        List<String> list = new ArrayList<>();        Stream<String> stream = list.stream(); //获取一个顺序流        Stream<String> parallelStream = list.parallelStream(); //获取一个并行流        //2. 通过 Arrays 中的 stream() 获取一个数组流        Integer[] nums = new Integer[10];        Stream<Integer> stream1 = Arrays.stream(nums);        //通过 Stream 类中静态方法 of()底层也是调用        Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);        //3.创建无限流,这两个底层调用的都是一样的        //迭代        Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);        stream3.forEach(System.out::println);        //生成        Stream<Double> stream4 = Stream.generate(Math::random).limit(2);        stream4.forEach(System.out::println);    }
Intermediate operation of the 1.2.2 stream

Multiple intermediate operations can be connected to form a pipeline, unless the pipeline triggers an abort operation, otherwise the intermediate operation will not perform any processing! It is called "lazy evaluation" when it is processed all at once when terminating the operation.

Filtering and slicing

Use

//筛选年龄<=35岁的员工@Testpublic void test2(){    //所有的中间操作不会做任何的处理    Stream<Employee> stream = emps.stream()            .filter((e) -> {                System.out.println("测试中间操作");                return e.getAge() <= 35;         });   //只有当做终止操作时,所有的中间操作会一次性的全部执行,称为“惰性求值”   stream.forEach(System.out::println);}//查询薪水>=5000的前三个员工@Testpublic void test4(){      emps.stream()            .filter((e) -> {             return e.getSal() >= 5000;      }).limit(3)            .forEach(System.out::println);  }//查询薪水>=5000的员工,去掉前两个    @Test    public void test5(){        emps.stream()                .filter((e) -> e.getSal()>= 5000)                .skip(2)//跳过2元素,返回一个扔掉了前2个元素的流                .forEach(System.out::println);    }//去重@Testpublic void test6(){     emps.stream()            .distinct()            .forEach(System.out::println);  }
Mapping

Example Application

    • Map
@Test    public void test1() {        List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");        //将传入的String值转为大写并返回String        Stream<String> stream = strList.stream()                .map(String::toUpperCase);        stream.forEach(System.out::println);        //传入的String,通过方法将String转化成包裹字符的stream了        Stream<Stream<Character>> stream2 = strList.stream()                .map(Stream2::filterCharacter);        stream2.forEach((sm) -> {            sm.forEach(System.out::println);        });    }    public static Stream<Character> filterCharacter(String str) {        List<Character> list = new ArrayList<>();        for (Character ch : str.toCharArray()) {            list.add(ch);        }        return list.stream();    }
    • FlatMap
//flatmap    @Test    public void Test3() {        List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");        Stream<Character> stream3 = strList.stream()                .flatMap(Stream2::filterCharacter);        stream3.forEach(System.out::println);    }
Sort


Practical use

@Test    public void test3() {        emps.stream()                .map(Employee::getName)                .sorted()                .forEach(System.out::println);        emps.stream()//按年龄排序,如果年龄相同:按名字排序                .sorted((x, y) -> {                    if (x.getAge() == y.getAge()) {                        return x.getName().compareTo(y.getName());                    } else {                        return Integer.compare(x.getAge(), y.getAge());                    }                }).forEach(System.out::println);    }
1.2.3 Stream's abort operation

Terminal operations generate results from the flow pipeline. The result can be any value that is not a stream, for example: List, Integer, or even void.

Find and Match

Return to about


Note: The connection between map and reduce is often referred to as the map-reduce mode because Google is known for its web search.

Use

    @Test    public void test1(){        //将数组中的值加起来        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);        Integer sum = list.stream()                .reduce(0, (x, y) -> x + y);        System.out.println(sum);        //使用map将员工的工资提取出来,使用reduce将工资累加        Optional<Double> op = emps.stream()                .map(Employee::getSal)                .reduce(Double::sum);        System.out.println(op.get());    }    //需求:搜索名字中 “六” 出现的次数    @Test    public void test2(){        Optional<Integer> sum = emps.stream()                .map(Employee::getName)                .flatMap(Stream2::filterCharacter)                .map((ch) -> {                    if(ch.equals(‘六‘))                        return 1;                    else                        return 0;                }).reduce(Integer::sum);        System.out.println(sum.get());    }
Collect

The implementation of the methods in the Collector interface determines how the stream performs collection operations (such as collection of List, Set, Map). However, the Collectors utility class provides a number of static methods that make it easy to create common collector instances, as shown in the following table:


2 New Time Date API2.1 using Localdate, localtime, LocalDateTime

Instances of the localdate, LocalTime, LocalDateTime classes are immutable objects that represent the date, time, date, and time of the use of the ISO-8601 calendar system. They provide a simple date or time and do not contain the current time information. Also does not contain time zone-related information.

The method provided:

Use

@Test public void Test () {localdate localdate = Localdate.now ();//The current date localtime localtime = localtime. Now ();//Current time LocalDateTime LocalDateTime = Localdatetime.now ();//Current Time and date System.out.println (localdate+ "==& gt; "    +localtime+ "==>" +localdatetime); } @Test public void Test2 () {localdate localdate = Localdate.of (1996, 02, 03);//Specify the current date localtime Loc Altime = Localtime.of (16, 04);//Specify the current time LocalDateTime LocalDateTime = Localdatetime.of (1996, 02, 03, 16, 04);//Specify Now    Date Time System.out.println (localdate+ "==>" +localtime+ "==>" +localdatetime);        } @Test public void Test3 () {localdate localdate = Localdate.now ();        Localdate localDate1 = localdate.plusdays (5);//Add 5 days to the current time localdate LocalDate2 = localdate.plusmonths (2);//plus 2 months Localdate localDate3 = localdate.plusweeks (1);//Plus one week localdate localDate4 = localdate.plusyears (1);//plus one year L Ocaldate localDate5 = localdate.minusmonths (5);Minus 5 days System.out.println (LOCALDATE4);        } @Test public void Test5 () {localdate localdate = Localdate.now (); Localdate localDate1 = Localdate.withdayofmonth (12);//change the number of days in the month to localdate localDate2 = Localdate.withyear (2 015);//Change the year in the date to localdate localDate3 = Localdate.withmonth (8);//Change the month of the date to August System.out.println (localdat    E3);        } @Test public void Test6 () {localdate localdate = Localdate.now ();    int year = Localdate.getyear ();//Gets the current years System.out.println;        } @Test public void Test7 () {localdate localdate = Localdate.now ();        Localdate localDate1 = Localdate.now (); Period Period = Localdate.until (localDate1);//Get date interval between two dates Boolean before = Localdate.isbefore (localDate1);//Compare two lo    Caldata Boolean leapyear = Localdate.isleapyear ();//Whether it is a leap year System.out.println (before); }
2.2 Duration and Period
    • Duration: Used to calculate two "time" intervals
    • Period: For calculation of two "date" intervals

Use

@Test    public void test4() {        //时间戳        Instant start = Instant.now();        try {            Thread.sleep(1000);        } catch (InterruptedException e) {        }        Instant end = Instant.now();        //Duration:用于计算两个“时间”间隔        Duration duration = Duration.between(start, end);        // Period:用于计算两个“日期”间隔        LocalDate localDate = LocalDate.now();        LocalDate localDate1 = LocalDate.of(2017, 12, 1);        Period period = Period.between(localDate, localDate1);        //给日期加一个间隔        LocalDate localDate3 = localDate.plus(period);        System.out.println(localDate3);    }
2.3 Parsing and formatting

Use Java.time.format.DateTimeFormatter to format time and date

@Test    public void test8() {        LocalDateTime localDateTime = LocalDateTime.now();        //第一种对时间日期的格式化方式        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy年MM月dd日 HH:mm:ss");        String format = formatter.format(localDateTime);        System.out.println(format);        //第二种对时间日期的格式化方式        String format1 = localDateTime.format(DateTimeFormatter.ofPattern("yy年MM月dd日"));        System.out.println(format1);    }
2.4 Time zone processing

Support for time zones was added to Java8, with time zones for: Zoneddate, Zonedtime, zoneddatetime where each time zone corresponds to an ID, and the region ID is in the format "{Region}/{City}" For example: Asia/shanghai, etc.

@Test    public void test9() {        //时区        LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));        System.out.println(ldt);    }
Default method in 3 interface and static method 3.1 interface

Java 8 allows an interface to include a method that has a specific implementation, which is called the default method, and the default keyword is used to decorate it.

3.1.1 Use of default methods

Such as

public interface MyInterface {    default String getName(){        return "呵呵呵";    }}

A class that implements this interface

public class SubClass implements MyInterface{}

Called in the main function

public static void main(String[] args) {        SubClass sc = new SubClass();        System.out.println(sc.getName());    }

Print results呵呵呵

The "class first" principle of the default method for 3.1.2 interfaces

If this subclass has a parent class, there is also a getname () method in the parent class

public class MyClass {    public String getName(){        return "嘿嘿嘿";    }}

Subclasses are now

public class SubClass extends MyClass implements MyInterface{}

This is then dropped in the main class.

public static void main(String[] args) {        SubClass sc = new SubClass();        System.out.println(sc.getName());    }

Result is嘿嘿嘿

Class Precedence principle: If a default method is defined in one of the ports, and another method with the same name is defined in the other parent class.
Select a method in the parent class. If the parent class provides a concrete implementation, the default method with the same name and parameters in the interface is ignored.

Interface violation for the default method of the 3.1.3 interface

"interface Conflict": if the subclasses implement multiple interfaces that have the same methods and parameters (regardless of whether the method is the default method), you must override the method to resolve the conflict

For example, another implemented interface for a subclass

public interface MyFun {    default String getName(){        return "哈哈哈";    }}

At this point the subclass must override the method, specifying which one to invoke through the interface name

public class SubClass implements MyFun,MyInterface{    @Override    public String getName() {        return MyInterface.super.getName();//指定调用的接口    }}

Called in the main class

public static void main(String[] args) {        SubClass sc = new SubClass();        System.out.println(sc.getName());    }

Execution Result:呵呵呵

Static methods in the 3.2 interface

In Java8, static methods are allowed in the interface.

Use

public interface MyInterface {    static void show(){        System.out.println("接口中的静态方法");    }}

Call directly using the class name

public static void main(String[] args) {        MyInterface.show();    }

Output Result:接口中的静态方法

Java8 full interpretation of two

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.