New features of JAVA 8

New features of Java8 include default methods, functional interfaces, lambda expressions, method references, Stream, Optional, and date API s.

1. Default method:

Methods in an interface can have method bodies, but they must have static or default modifiers. Other methods are abstract methods. Static-modified methods cannot be inherited by subinterfaces, methods cannot be overridden, they can only be called by class name.method name; default-modified methods can be inherited by subinterfaces, orTo be overridden, the call is made through the object implementing the class.

2. Functional interfaces:

There is only one abstract method in an interface, and generally there is a @FuntionalInterface annotation, even if it is not, it is a functional interface.

Common functional interfaces: Comparetor, Runnable.

3. lambda expression:

You can think of it as a shortcut to an anonymous internal class, and the interface using a lambda expression must be a functional interface.

Note: Anonymous internal classes compile to produce two class files, but lambda expressions compile to produce only one class file.

 

(Parameter 1, parameter 2...) denotes a list of parameters; ->denotes a connector; {} is the method body inside
1, = The type on the right is automatically inferred based on the type of functional interface on the left;
(2) If the parameter list is empty, just keep ();
3. If there is only one parameter, () can be omitted, only the name of the parameter is needed;
(4) If only one sentence is executed and there is no return value, {} can be omitted, if there is a return value, {} must be omitted at the same time and only one sentence is guaranteed to be executed;
5. The data type of the parameter list is automatically inferred;

6. Local variables used in lambda expressions are modified by final by default, whether they are defined in or outside the lamdba expression.So as long as it is a local variable used in a lambda expression, it cannot be modified anywhere.

 

4. Method Citation:

4.1 Construction Method References:

//Anonymous Inner Class
PersonFacotry facotry = new PersonFacotry() {
  @override
  public Person createPerson(String name, Integer age){ 
    //Other operations
    return new Person (name, age);
  }
};
//lambda Expression Writing
PersonFacotry facotry1 = (name, age) -> new Person (name, age);

//lambda Short form of expression (Functional interface with this notation has several parameters,Call its construction method for the number of corresponding parameters)
PersonFacotry facotry2 = Person:: new;

Person person = facotry.createPerson ( name: "Someone", age: 100) ;
System.out.println(person);

    

4.2 Static Method References

public class Test{
    public static void main(string[] args) {
        //Anonymous Internal Class Method
        Parseinterface pil = new ParseInterface(){ 
            @override
            public int parse(string str) {
                 return Integer.parselnt(str);
            }
        };

         // Lambda Expression Normal Writing
         ParseInterface pi2 = str->Integer.parseInt(str);

        // Lambda Short Form
        ParseInterface pi3 = Integer::parseInt;   
    }
}     

 

4.3 Instance Method Reference

Java 1.8 provides a functional interface, Function, that accepts two parameters

 

Anonymous Internal Class Style

    string str ="Hello.world";
    //Ways to anonymize internal classes
    Function<String,Boolean> func1= new Function<String,Boolean> (){
        @override
        public Boolean apply(strinq suffix) {
             return str.endswith (suffix);
        }
    };    

 

General Writing of Lambda Expressions

// Lambda Expression Normal Writing
String str = "Hello.world";
Function<String,Boolean> func3 = t -> str.endsWith(t);
System.out.println(func3.apply("world"));

 

Short form of Lambda expression

// Lambda Expression Normal Writing
String str = "Hello.world";
Function<String,Boolean> func2 = t -> str::endsWith;
System.out.println(func2.apply("world"));

 

5. Stream:

The Java 8 API adds a new abstract called Stream, which greatly increases the productivity of Java programmers and allows them to write efficient, clean and concise code.

Note: Streams in IO are completely different.

In Java 8, a collection interface has two methods to generate streams:

Stream()Creates a serial stream for a collection.(Common)

ParallelStream()Creates parallel streams for collections.

Stream common methods:

  ForEach:

Stream provides a new method,'forEach', to iterate over each data in the stream.The following code snippet uses forEach to output 10 random numbers:

Random random = new Random();

random.ints().limit(10).forEach(System.out::println);

  map:

The map method is used to map each element to its corresponding result, and the following code snippet uses map to output the corresponding square number of elements:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

// Get the corresponding square number 

List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

  filter:

The filter method is used to filter out elements by setting conditions.The following snippet filters out empty strings using the filter method:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); 

// Gets the number of empty strings
int count = strings.stream().filter(string -> string.isEmpty()).count();

  limit:

The limit method is used to get a specified number of streams.The following snippet prints 10 pieces of data using the limit method:

Random random = new Random();

random.ints().limit(10).forEach(System.out::println);

  sorted:

The sorted method is used to sort streams.The following code snippet uses the sorted method to sort the 10 random numbers output:

Random random = new Random();

random.ints().limit(10).sorted().forEach(System.out::println);

parallel programs:

ParallelStream is an alternative method of stream parallel processing.The following example uses parallelStream to output the number of empty strings:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");

// Gets the number of empty strings 

int count = strings.parallelStream().filter(string -> string.isEmpty()).count();

* We can easily run in sequence and switch directly in parallel.

  Collectors:

The Collectors class implements many reduction operations, such as converting streams into collections and aggregation elements.Collectors can be used to return lists or strings:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");

List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

System.out.println("Filter List: " + filtered);

String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));

System.out.println("Merge String: " + mergedString);

 

6. Optional:

Optional objects can be null, so the introduction of the Optional class is a good solution to null pointer exceptions.

Understand the use of the Optional class through the following examples:

Public class User{

  private String name;

  private String password;

  ....

}

Previous judgments:

public class Mytest{

  public static void main(String[] args){

       User user = new User();

    User.setPassword("admin");

    String name = getPwd(user);

    System.out.println(name);

  }

  public static String getPwd(User u){

    if(u==null){

      return "unknown";

  }

   return u.getPassword();

}

 

Use Optional:

public static String getPwd(User u){

  return Optional.ofNullable(u)

          .map(user->user.getPassword())

          .orElse("unknown");

};

 

7. Date Api:

Jdk1.8 gives us three local date-time classes: LocalDate, LocalTime, and LocalDateTime.

Use the LocalDate, LocalTime, and LocalDateTime API s when you don't need to deal with time zone issues:

// Get the current date and time

 LocalDateTime currentTime = LocalDateTime.now();

 System.out.println("current time: " + currentTime);

LocalDate date1 = currentTime.toLocalDate();

System.out.println("date1: " + date1);

Month month = currentTime.getMonth();

int day = currentTime.getDayOfMonth();

int seconds = currentTime.getSecond();

System.out.println("month: " + month +", day: " + day +", second: " + seconds);

 

Use the ZonedDateTime API for time zones when they need to be processed:

ZonedDateTime dd= ZonedDateTime.now();
System.out.println(dd);
ZonedDateTime date1 = ZonedDateTime.parse(dd.toString());
System.out.println("date1: " + date1);
ZoneId id = ZoneId.of(ZoneId.SHORT_IDS.get("CTT"));
System.out.println("ZoneId: " + id);
ZoneId currentZone = ZoneId.systemDefault();
System.out.println("Current Period Time Zone: " + currentZone);

Tags: Java Lambda

Posted on Wed, 04 Sep 2019 17:53:21 -0700 by mrbippy