java_day12_jdk1.8 new features

1. Default interface
Java 8 interface to allow us to add a non-abstract method implementation, you can just use the default keyword, also called the extension method
// Formula calculation formula represents the interface design of a
public interface Formula {
// calculating
public Double the calculate (A int);

// prescribing
default Double sqrt (int A) {
return the Math.sqrt (A);
}
}

main:
Formula f = new Formula() {
@Override
public double calculate(int a) {
return a+1;
}
};
System.out.println(f.calculate(4));
System.out.println(f.sqrt(8));

Note: You can also now interfaces exist static methods, you can use the interface name in the form of a static method name called directly.


2.Lambda expression
2.1 appreciated Lambda expressions
example:
public class LambdaTest1 {

public static void main (String [] args) {

// If the elements of a list opportunity to sort
List <String> list = Arrays.asList ( "hello "," tom "," apple "," bbc ");
sorting before // we can write
Collections.sort (List, new new Comparator <String> () {
@Override
public int the Compare (O1 String, String o2) {
return -o1.compareTo (O2);
}
});

// Lambda expressions using
the Collections.sort (List, (S1 String, String S2) -> {
return s1.compareTo (S2);
});

// can abbreviated
// 1 inside the braces to a code.
@ 2 compiler can automatically deduce the parameter type.
the Collections.sort (List, (S1, S2) -> s1.compareTo (S2));

the System.out.println(list);

}

}


2.2 Functional Interface
"interface function" refers to an abstract method include only the interface, each interface function type lambda expressions are automatically matched to the abstract methods. Because the default method is not abstract methods, so you can give your function interface add the default method.
We can be a lambda expression as any type of interface contains only an abstract method, in order to ensure that your interface is really meet this requirement, you can add @FunctionalInterface comment on the interface, the compiler if you find this comment marked interface has when more than one abstract method will complain.
For example:

// This comment can not be added, plus just to make the compiler checks
@FunctionalInterface
interface Action {
public void RUN ();

void doSomething default () {
System.out.println ( ".. doSomething");
}
}
// add an annotation may, just to allow the compiler to add check
@FunctionalInterface
interface Work <T, V> {
public V the doWork (T T);
}

public class LambdaTest2 {

public static void test(Action a){
a.run();
a.doSomething();
}

public static void run(Work<String,Integer> a){
int i = a.doWork("hello");
System.out.println(i);
}

static void main public (String [] args) {

// implementation of the original inner class
Test (the Action new new () {
@Override
public void RUN () {
System.out.println ( "RUN ..");
}
}) ;

// the lambda expression method
test (() -> System.out.println ( "run"));


// Alternatively, you can create objects
Action A = () -> System.out.println ( "RUN ...");
System.out.println (a.getClass ());
the Test (A);

// There are generic interface may only concern the method parameters and return values
Work <String, Integer> = W (V) -> v.length ();
RUN (W);

run((v)->v.length());

// If only one parameter, you also can do shorthand: remove the parentheses
// Note that the code on the way, as a return value, then do not write return
RUN (V-> v.length ());

// how sentence code, it {} a need to write, and the need to write return
RUN (V -> {
System.out.println ( "the doWork ..");
return v.length ();
});

// The following code is what is meant observation
RUN (V->. 1);

}

}

Note: lambda expression can not be represented in the interface default method of rewriting, lambda expression to match only the only abstract methods corresponding to the interface. Lambda expression equivalent to only implement the abstract methods.


2.3 Method constructor reference
Java 8 :: allows you to use keywords to pass methods (static methods and non-static method)
, for example:
public class LambdaTest3 {

public static void main (String [] args) {

// this is normally used
Action3 a1 = v-> "number is received:" + V;
System.out.println (a1.run (. 5));

// Integer class reference using a Lambda Static method
Action3 toBinaryString :: A2 = Integer;
System.out.println (a2.run (10));

// the referenced object using a Lambda LambdaTest3 class of non-static methods
LambdaTest3 t = LambdaTest3 new new ();
Action3 A3 Test :: = T;
System.out.println (a3.run (20 is));
}

public String Test (I int) {
return "= I" + I;
}

}
@FunctionalInterface
interface Action3{
public String run(int i);
}

Note: the equivalent lambda expression reference implementation using another class as a method to achieve Action3 interface run method, provided that both the parameter list and return type of a method must be consistent

you can cite reasons Integer class of static methods toBinaryString is:. Action3 interface is only one way and the method parameter types and return value type parameter type Integer class static method toBinaryString, the return type is the same reason you can reference non-static methods, too

 


The following is an example of a time band generic interface: :: class name may be used in the form of non-static method reference method
NOTE: There are also generic when using
public class LambdaTest3Pro {

public static void main (String [] args) {

the Model new new m = the Model ();

// these are written
// v corresponds to the variable parameter is received in the run method, and then call its methods using v, v is the type Model, as used herein, generic
Action3Pro <the Model> A1 = V-> v.test1 ();
Action3Pro <the Model> A1 = V-> v.test2 ( "Hello");
Action3Pro <the Model> A1 = V-> v.test3 ();
a1.run (m);

// in this case, it may also be a method using a Model internal reference
// but must meet the following requirements:
//1.run method parameter type Model [must]
// references [2 method. ] must be no argument
method // future run method is invoked automatically by the mass m of the object referenced
Action3Pro <Model> a2 = the Model :: test1;
a2.run (m);
or
Action3Pro <Model> a2 Test3 the Model :: =;
a2.run (m);

// compiler error because no parameters test2 not
Action3Pro <the Model> A2 = the Model :: test2;
a2.run (m);

}

}

interface Action3Pro<T>{
public void run(T t);
}

class Model{

public void test1(){
System.out.println("test1");
}
public void test2(String s){
System.out.println("test2");
}
public int test3(){
System.out.println("test3");
return 1;
}
}

 

Java 8 allows you to use keywords to quote :: constructor
public class LambdaTest4 {

public static void main (String [] args) {

// the Lambda expression refers to the constructor
// constructor parameters according to which structure to use automatic matching is
// here, when a create method will automatically call reference has Action4 class constructor
Action4Creater a new new :: = Action4;
Action4 A4 = a.create ( "zhangsan");
a4.say ();


}

}

class Action4{
private String name;
public Action4() {

}
public Action4(String name) {
this.name = name;
}
public void say(){
System.out.println("name = "+name);
}
}

interface Action4Creater{
public Action4 create(String name);
}

 


2.4 lambda expression variable access
public class LambdaTest5 {
Private static int J;
Private int K;
public {static void main (String [] args)
LambdaTest5 LambdaTest5 new new = T ();
t.test ();
}

public void Test () {
int NUM = 10;
J = 20 is;
K = 30;

// the lambda expression can access the member variables methods may be local variables
Action5 a5 = (i) - after> System.out.println ( ": i. = "+ (i + NUM + J + k));
a5.run (1);

// but this variable is accessed by default become final no longer be modified or changed not by the compiler
// NUM = 60;
J = 50;
K = 70;
}

}

interface Action5{
public void run(int i);
}



2.5 java.util.function.Predicate <T> Interface
Predicate interface is used to support the new java programming interface function, and the use of this interface can be lambda expressions with less code to the API method of adding more the dynamic behavior.
{class PredicateTest public
public static void main (String [] args) {
List <String> Arrays.asList List = ( "the Java", "HTML5", "the JavaScript", "C ++", "Hibernate", "the PHP");

// display all
filter (List, name-> to true);
// do not show the whole
filter (list, name-> false) ;

Begin // J is language
filter (List, name-> name.startsWith ( "J"));
// end. 5
filter (list, name-> name.endsWith ( "5"));

// length greater than the display name. 4
filter (List, name-> name.length ()>. 4);

System.out.println ( "-----------------------");
// name beginning with J and a length greater than 4.
Predicate <String> c1 = name-> name.startsWith ( "J");
the Predicate <String> C2 = name-> name.length ()>. 4;
filter (List, c1.and (C2));

// the name does not begin with J
the Predicate < String> C3 = (name) -> name.startsWith ( "J");
filter (List, c3.negate ());

// name of J at the beginning or length of less than 4
c4 = name- Predicate <String>> name .startsWith ( "J");
the Predicate <String> C5 = name-> name.length () <. 4;
filter (List, c4.or (C5));

// static methods can also be used directly Predicate interface
// Java name for the
filter (list, Predicate.isEqual ( "Java "));

//判断俩个字符串是否相等
boolean test = Predicate.isEqual("hello").test("world");
System.out.println(test);
}
public static void filter(List<String> list, Predicate<String> condition) {
for(String name: list) {
if(condition.test(name)) {
System.out.println(name + " ");
}
}
}

}

 

2.6 java.util.function.Function <T, R> Interface
Function interface has an argument and return a result, and comes default methods can be combined with other functions
compose method represents a method performed prior
andThen shows a method after a method executes
Note: after you compose and andThen method calls will return to the object itself, which can be easily programmed chain

public interface Function<T, R> {

R apply(T t);

default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}

default <V> Function <T, V> andthen (Function After <R & lt Super, the extends V??>) {
Objects.requireNonNull (After);
return (T T) -> after.apply (Apply (T));
}

// Note: t-> t is (t) -> t shorthand
// t-> t identity as the return value of the method, the object is of type Function
// wording like this: Function <Object, Object > T-F => T;
// then f.apply ( "test") returns the string "Test"
// returns what incoming
static <T> Function <T, T> Identity () {
return T - > T;
}
}

For example:
public class FunctionTest {
// internal static type
Private static class Student {
Private String name;
public Student (String name) {
this.name = name;
}
public String getName () {
return name;
}

}
public static void main ( String [] args) {
/ * user registration enter a name Tom * /
String name = "Tom";

/ * create an object * / use the name of the user's input
Function <String, Student> f1 = (s) -> new Student (S);
// Note that the above code can be written so that references class constructors
// Function <String, Student> :: F1 = new new Student;
Student STU1 = f1.apply (name);
the System. out.println (stu1.getName ());

/ * needs to change, before you create the Student object using the name needs to add a name prefix * /
Function <String, String> before = (S) -> "briup _" + S;
// representation performed first before the object before the f1 call, the method before the object is returned as a result of the parameter f1 object method
Student stu2 = f1. Compose (before) .apply (name);
System.out.println (stu2.getName ());

/ * get the name of the created object length * /
Function <Student, Integer> = After (STU) -> stu.getName () length ();.
// before first calling method, the result as a parameter to the method call to f1, f1 results after completion of the method call and then passed as a parameter after, the result is that we receive the data
int len = f1.compose (before) .andThen (After) .apply (name);
System.out.println (len);

}

}

 

2.7 java.util.function.Supplier <T> Interface
Supplier interfaces return a value of any paradigm, and Function interfaces except that the interface has no parameters
public interface Supplier <T> {
T GET ();
}
example:
public class {SupplierTest
public static void main (string [] args) {
// generates a random string of eight
Supplier <string> F = () -> {
string Base = "abcdefghijklmnopqrstuvwxyz0123456789";
the random random new new = the random ();
the StringBuffer the StringBuffer new new = SB ();
for (int I = 0; I <. 8; I ++) {
// generated [0, a random number between base.length)
int = number random.nextInt (base.length ());
sb.append (base.charAt (Number));
}
return sb.toString ();
};

System.out.println(f.get());
}

}


2.8 java.util.function.Consumer <T> Interface
Consumer paradigm interface receives an arbitrary value, and Function interfaces except that the interface has no value
public interface Consumer <T> {

void accept(T t);

default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
例如:
public class ConsumerTest {
//静态内部类
private static class Student{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

public static void main(String[] args) {
Student s = new Student();
s.setName("tom");

Consumer<Student> first = stu->{
System.out.println("我要第一个执行,把name值给改了");
stu.setName("zhangsan");
};
Consumer <Student> = the then STU -> {
System.out.println ( "I followed execution, name of the output value of:" + stu.getName ());
};
first.andThen (the then) .accept (S );

}

}

Summary:
Function <T, R & lt> Interface R apply (T t); have arguments returns a value
Supplier <T> Interface T get (); no parameters return value
Consumer <T> Interface void accept (T t); have arguments no return value

Also note interface: using the manner described above and its use interfaces similar
BinaryOperator <T> Interface T apply (T t, T t ) of the two T as input and returns as output a T
Note: the type generally used in the same the combined data
BiFunction <T, U, R> Interface R apply (T t, U u ) and a T to a U input and returns as output a R
Note: two different types of data, obtained in the third types of data

Note: BinaryOperator interface extends BiFunction Interface
public interface BinaryOperator <T> extends BiFunction <T, T, T>

BiConsumer <T, U> Interface void accept (T t, U u) passing the two parameters, no return value


Note: according to the specific functional requirements, to customize their own interface function

 


2.9 java.util.Optional <T> class
Optional interfaces rather than a class, which is used to prevent a NullPointerException type auxiliary
Optional is defined as a simple container, which value may be null or not null. Before Java8 general function should return a non-null object but occasionally it may return a null, while in Java8, but do not recommend you return null return Optional.
This is a container object can be a null. If the value exists isPresent () method returns true, call the get () method returns the object.
{class OptionalTest public

public static void main (String [] args) {

/ * Optional of an object to the method creates a non-null value * /
// Note that incoming parameters when creating an object can not be null.
// if the incoming parameter is null, throw NullPointerException.
Optional <String> Optional.of OP1 = ( "Hello");

/ * Optional ofNullable method creates a specified value, if the specified value is null, it returns a null Optional. * /
// ofNullable and of similar methods, the only difference is acceptable or null case
Optional The <String> OP2 = Optional.ofNullable (null);

/ * If the value exists isPresent method returns true, otherwise returns false. * /
/ * get Optional method If there is value will be returned, otherwise throw NoSuchElementException. * /
IF (op1.isPresent ()) {
System.out.println (op1.get ());
}
IF (op2.isPresent ()) {
System.out.println (op2.get ());
}

/ * ifPresent method if the method has a value Optional instance consumer interface for its call, or not treated * /
// method consumer interface only parameter does not return value
// public void accept (T t) ;

op1.ifPresent (STR-> System.out.println (STR));
op2.ifPresent (STR-> System.out.println (STR)); // this is not executed because there op2 value is null


/ * Method orElse If there is value will be returned, otherwise other specified value. * /
System.out.println (op1.orElse () "op1 if the return value is null words");
System.out.println (op2.orElse ( "op2 if the value returned is null in this words "));


/ * orElseGet orElseGet and orElse method analogous method, except that the default values in different ways obtained. The method orElse incoming string as the default value, orElseGet Supplier interfaces implemented acceptable methods used to generate the default values. * /
// Supplier interface method does not return a value, but parameters
// public GET T ();
System.out.println (op1.orElseGet (() -> "own definition of the return value"));
the System.out .println (op2.orElseGet (() -> " own definition of the return value"));


/ * orElseThrow method if there is value will be returned, otherwise throw supplier interface to create exceptions. * /
// orElseThrow we can pass in a lambda expression or method, if the value does not exist to throw an exception.
// orElseThrow declare all of the following methods can only return an object of type Throwable
//public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X

{the try
System.out.println (op1.orElseThrow (Exception :: new new));
//System.out.println(op2.orElseThrow(NullPointerException::new)); this will throw an exception
} catch (Exception e) {
e.printStackTrace ();
}


/ * if any value Map method, the calling function and the mapper process return value * /
// return value Optional the wrapped and still, and the generic type which matches your return value
// public <U> Optional <U> map (Function <? super T,? extends U> mapper)

Optional <Integer> = MAP1 op1.map (STR->. 1);
System.out.println (map1.orElse (0));
optional <Double> MAP2 = op2.map (STR-> 1.2);
the System.out. the println (map2.orElse (0D));


/ * flatMap method if the value of the function call returns mapper Optional return type, or null otherwise Optional. * /
// flatMap similar method to map, except that the mapper flatMap return value must be Optional.
// When you call ended, flatMap will not result with Optional package
// we need to own the return value encapsulates Optional
// public <U> Optional <U> flatMap (Function <? Super T,
Optional <U >> Mapper) ;

Optional <String> flatMap = op1.flatMap (STR-> Optional.of (STR + "_ briup"));
System.out.println (flatMap.get ());
// compiler error because the function of the return type of the lambda represents not
//op1.flatMap (str-> "");

/ * filter value, and if the method satisfies the predicate condition comprising Optional return value, otherwise empty Optional. * /
// Optional The public <T> filter (the Predicate the predicateA <Super T?>);

OP1 = op1.filter (STR-> str.length () <10);
System.out.println (op1.orElse ( "value is null "));
OP1 = op1.filter (STR-> str.length ()> 10);
System.out.println (op1.orElse (" is null "));
}

 

Guess you like

Origin www.cnblogs.com/yue-170305/p/11478939.html