Java8新特性

44 阅读1分钟

Stream

并行流

原理:forkjoin框架:采用工作窃取模式提高cpu利用率。

public class ForkjoinTest {
    public static void main(String[] args) {
        /*long reduce = LongStream.range(0, 101).parallel().reduce(0, Long::sum);
        System.out.println(reduce);*/

        Instant start = Instant.now();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        Long invoke = forkJoinPool.invoke(new ForkJoinCal(0L, 10000000L));
        Instant end = Instant.now();
        System.out.println("method spend time:" + Duration.between(start, end).toMillis() + "ms");
        System.out.println(invoke);
    }
}

class ForkJoinCal extends RecursiveTask<Long> {

    private Long start;
    private Long end;
    private Long threshold = 10000L;

    public  ForkJoinCal(Long start, Long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        Long length = end - start;
        if (length <= threshold) {
            long sum = 0;
            for (long i = start; i <= end ; i++) {
                sum += i;
            }
            return sum;
        } else {
            Long mid = (start + end) / 2;
            ForkJoinCal left = new ForkJoinCal(start, mid);
            left.fork();
            ForkJoinCal right = new ForkJoinCal(mid + 1, end);
            right.fork();
            return left.join() + right.join();

        }
    }
}

Optional容器类

Optional提供很多有用的方法,这样我们就不用显式进行空值检测。

  • 建Optional类对象的方法:

    1. Optional.of(T t) : 创建一个 Optional 实例,t必须非空;
    2. Optional.empty() : 创建一个空的 Optional 实例
    3. Optional.ofNullable(T t):t可以为null
  • Optional容器中是否包含对象:

    1. boolean isPresent() : 判断是否包含对象
  • Optional容器的对象:

    1. T get(): 如果调用对象包含值,返回该值,空则抛异常
    2. T orElse(T other) :如果有值则将其返回,否则返回指定的other对象。
    3. T orElseGet(Supplier other) :如果有值则将其返回,否则返回由 Supplier接口实现提供的对象。

新日期和时间API

获取线程安全的日期格式类

private static final ThreadLocal<DateFormat> formatter = new ThreadLocal<DateFormat>(){
    @Override
    protected DateFormat initialValue() {
        return new SimpleDateFormat("yyyyMMdd");
    }
};
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

LocalDate,LocalTime,LocalDateTime

LocalDate now = LocalDate.now();
System.out.println(now);

LocalDate of = LocalDate.of(2022, 12, 12);
System.out.println(of);

LocalDate localDate1 = now.plusYears(1);
LocalDate localDate2 = localDate1.minusMonths(2);
System.out.println(localDate2);

Month month = now.getMonth();
int monthValue = now.getMonthValue();
System.out.println(monthValue);

DayOfWeek dayOfWeek = now.getDayOfWeek();
System.out.println(dayOfWeek.toString());

// 指定时间参数
LocalDate localDate = now.withMonth(1);
System.out.println(localDate);

Instant时间戳(从1970年1月1日到某个时间之间的毫秒值)

Instant now1 = Instant.now();
OffsetDateTime now2 = now1.atOffset(ZoneOffset.ofHours(8));
long l = Instant.now().toEpochMilli();
System.out.println(l);
Instant instant = Instant.ofEpochMilli(1000L);
System.out.println(instant);

Duration时间间隔,Period日期间隔

Instant start = Instant.now();
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    throw new RuntimeException(e);
}
Instant end = Instant.now();
// 获取时间间隔毫秒
System.out.println(Duration.between(start, end).toMillis());

LocalDateTime localDateTime1 = LocalDateTime.now();
LocalDateTime localDateTime2 = localDateTime1.plusMinutes(1);
// 获取时间间隔毫秒
System.out.println(Duration.between(localDateTime1, localDateTime2).toMillis());


LocalDate l1 = LocalDate.now();
LocalDate l2 = LocalDate.of(2022, 12, 15);
// 获取日期间隔毫秒
System.out.println(Period.between(l1, l2).getDays());

TemporalAdjusters时间矫正器

LocalDateTime localDateTime = LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth());
System.out.println(localDateTime);

ZoneDate,ZoneTime,ZoneDateTime

Set<String> zoneIds = ZoneId.getAvailableZoneIds();
System.out.println(zoneIds);
    
LocalDateTime localDateTime1 = LocalDateTime.now(ZoneId.of("Africa/Khartoum"));
System.out.println(localDateTime1);
    
ZonedDateTime zonedDateTime = localDateTime1.atZone(ZoneId.of("Europe/Monaco"));
System.out.println(zonedDateTime);