美文网首页
JDK8新特性

JDK8新特性

作者: Ary_zz | 来源:发表于2020-02-28 17:40 被阅读0次

2020-02-28

link

接口

// 默认方法
public interface IAnimal {
    default void breath(){
        System.out.println("breath!");
    }
    // 静态方法
    static void run(){}
}

Optional

java.util.stream

// Calculate total points of all active tasks using sum()
final long totalPointsOfOpenTasks = tasks
    .stream()
    .filter( task -> task.getStatus() == Status.OPEN )
    .mapToInt( Task::getPoints )
    .sum();

functionInterface

lambda

方法引用

public class MethodReferenceTest {

    public static void main(String[] args) {
        ArrayList<Car> cars = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Car car = Car.create(Car::new);
            cars.add(car);
        }
        cars.forEach(Car::showCar);

    }

    @FunctionalInterface
    interface Factory<T> {
        T create();
    }

    static class Car {
        public void showCar() {
            System.out.println(this.toString());
        }

        public static Car create(Factory<Car> factory) {
            return factory.create();
        }
    }
}

time

clock

// Get the system clock as UTC offset 
final Clock clock = Clock.systemUTC();
System.out.println( clock.instant() );
System.out.println( clock.millis() );

duration

// Get duration between two dates
final LocalDateTime from = LocalDateTime.of( 2014, Month.APRIL, 16, 0, 0, 0 );
final LocalDateTime to = LocalDateTime.of( 2015, Month.APRIL, 16, 23, 59, 59 );

final Duration duration = Duration.between( from, to );
System.out.println( "Duration in days: " + duration.toDays() );
System.out.println( "Duration in hours: " + duration.toHours() );

base64

final String text = "Base64 finally in Java 8!";
final String encoded = Base64
            .getEncoder()
            .encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
System.out.println( encoded );
        
final String decoded = new String( 
  Base64.getDecoder().decode( encoded ),
  StandardCharsets.UTF_8 );
System.out.println( decoded );

parallel array

public class ParallelArrays {
    public static void main( String[] args ) {
        long[] arrayOfLong = new long [ 20000 ];        
        
        Arrays.parallelSetAll( arrayOfLong, 
            index -> ThreadLocalRandom.current().nextInt( 1000000 ) );
        Arrays.stream( arrayOfLong ).limit( 10 ).forEach( 
            i -> System.out.print( i + " " ) );
        System.out.println();
        
        Arrays.parallelSort( arrayOfLong );     
        Arrays.stream( arrayOfLong ).limit( 10 ).forEach( 
            i -> System.out.print( i + " " ) );
        System.out.println();
    }
}

completeableFuture

https://juejin.im/post/5adbf8226fb9a07aac240a67

CompletableFuture<String> completableFuture = new CompletableFuture<String>();
String result = completableFuture.get()
completableFuture.complete("Future's Result")

// async
CompletableFuture<Void> future = CompletableFuture.runAsync(new Runnable() {
    @Override
    public void run() {
        // Simulate a long-running Job
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        System.out.println("I'll run in a separate thread than the main thread.");
    }
});

// Block and wait for the future to complete
future.get()

// get result
CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
    @Override
    public String get() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        return "Result of the asynchronous computation";
    }
});

// Block and get the result of the Future
String result = future.get();


// callback list
CompletableFuture<String> welcomeText = CompletableFuture.supplyAsync(() -> {
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
       throw new IllegalStateException(e);
    }
    return "Rajeev";
}).thenApply(name -> {
    return "Hello " + name;
}).thenApply(greeting -> {
    return greeting + ", Welcome to the CalliCoder Blog";
});

System.out.println(welcomeText.get());
// Prints - Hello Rajeev, Welcome to the CalliCoder Blog

// thenAccept() example
CompletableFuture.supplyAsync(() -> {
    return ProductService.getProductDetail(productId);
}).thenAccept(product -> {
    System.out.println("Got product detail from remote service " + product.getName())
});

// thenRun() example
CompletableFuture.supplyAsync(() -> {
    // Run some computation  
}).thenRun(() -> {
    // Computation Finished.
});

相关文章

  • JDK8新特性介绍

    JDK8新特性介绍 JDK8新特性:​ 1,Lambda表达式​ 2,新的日期API​ 3,引入Optional​...

  • jackson parser LocalDataTime 问题

    jackson parser LocalDataTime 问题 LocalDataTime 是 jdk8 的新特性...

  • 面试

    sql语句 jdk8新特性 lamed 测试单元测试

  • @FunctionalInterface函数式接口

    JDK8新特性:函数式接口@FunctionalInterface的使用说明

  • FunctionalInterface函数式接口

    关于jdk8的新特性函数式接口示例以及描述 代码示例

  • JDK8新特性

    Lambda语法 Lambda是什么? "Lambda表达式"(Lambda expression)是一个匿名函数...

  • jdk8新特性

    API:http://docs.oracle.com/javase/8/docs/api/ 新特性:http://...

  • JDK8 新特性

    为什么要学Java8 Java8让你的编程变得更容易 充分稳定的利用计算机硬件资源 Lambda lambda 是...

  • jdk8新特性

    Jdk8相对之前的jdk加入了很多的新特性。 1:jdk中加入了default关键字。 在java里面,我们通常都...

  • jdk8新特性

    默认方法。一个在接口里面有了一个实现的方法。只需在方法名前面加个 default 关键字即可实现默认方法。 lam...

网友评论

      本文标题:JDK8新特性

      本文链接:https://www.haomeiwen.com/subject/zkjlhhtx.html