//這是錯誤的
int num = 2;
Function stringConverter = (from) -> from * num;
num++;//會報錯,因為此時num已經(jīng)是final聲明的了
System.out.println(stringConverter.apply(3));
public class Mule implements IHorse,IAnimal{
@Override
public void eat() {
System.out.println(“Mule eat”);
}
public static void main(String[] args) {
Mule m=new Mule();
m.run();
m.breath();
}
}
注意上述代碼中Mule實例同時擁有來自不同接口的實現(xiàn)方法。在這Java 8之前是做不到的。從某種程度上說,這種模式可以彌補Java單一繼承的一些不便。但同時也要知道,它也將遇到和多繼承相同的問題,如果IDonkey也存在一個默認的run()方法,那么同時實現(xiàn)它們的Mule,就會不知所措,因為它不知道應該以哪個方法為準。此時,由于IHorse和IDonkey擁有相同的默認實例方法,故編譯器會拋出一個錯誤:Duplicate default methods named run with the parameters () and () are inherited from the types IDonkey and IHorse
public interface StaticFunInterface {
public static int find(){
return 1;
}
}
public class TestStaticFun {
public static void main(String[] args){
//接口中定義了靜態(tài)方法 find 直接被調(diào)用
StaticFunInterface.fine();
}
}
Arrays.stream(Xxx[] array) Returns a sequential Int/Long/DoubleStream with the specified array as its source.
XxxStream.empty() Returns an empty sequential Int/Long/DoubleStream .
XxxStream.generate(XxxSupplier s) Returns an infinite sequential unordered stream where each element is generated by the provided Int/Long/DoubleSupplier .
XxxStream.iterate(Xxx seed, XxxUnaryOperator f) Returns an infinite sequential ordered Int/Long/DoubleStream like as Stream.iterate(T seed, UnaryOperator f)
XxxStream.of(Xxx... values) Returns a sequential ordered stream whose elements are the specified values.
XxxStream.concat(XxxStream a, XxxStream b) Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.
Int/LongStream.range(startInclusive, endExclusive) Returns a sequential ordered Int/LongStream from startInclusive (inclusive) to endExclusive (exclusive) by an incremental step of 1.
Int/LongStream.rangeClosed(startInclusive, endInclusive) Returns a sequential ordered Int/LongStream from startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1.
C、其他 C.1、I/O Stream
BufferedReader.lines()
C.2、File Stream
Files.lines(Path path)
Files.find(Path start, int maxDepth, BiPredicate matcher, FileVisitOption... options)
distinct() Returns a stream consisting of the distinct elements (according to Object.equals(Object) ) of this stream.
limit(long maxSize)
skip(long n)
sorted(Comparator super T> comparator)
map(Function super T,? extends R> mapper) Returns a stream consisting of the results of applying the given function to the elements of this stream.
flatMap(Function super T,? extends Stream extends R>> mapper) Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the - provided mapping function to each element.
peek(Consumer super T> action) Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.
這里著重講解下 flatMap() 假設我們有這樣一個字符串list: List strs = Arrays.asList("hello", "alibaba", "world"); 如何列出里面各不相同的字符呢?
reduce(BinaryOperator accumulator) Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.
toArray()
forEach(Consumer super T> action)
forEachOrdered(Consumer super T> action) Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.
collect(Collector super T,A,R> collector) Performs a mutable reduction operation on the elements of this stream using a Collector .
List ss =new ArrayList();
...
double ave = ss.parallelStream().mapToInt(s->s.score).average().getAsDouble();
int[]arr = new int [10000000];
Arrarys.parallelSort(arr);
// 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() );
//日期算術操作,多數(shù)日期/時間API類都實現(xiàn)了一系列工具方法,如:加/減天數(shù)、周數(shù)、月份數(shù),等等。還有其他的工具方法能夠使用TemporalAdjuster調(diào)整日期,并計算兩個日期間的周期。
LocalDate today = LocalDate.now();
//Get the Year, check if it"s leap year
System.out.println("Year "+today.getYear()+" is Leap Year? "+today.isLeapYear());
//Compare two LocalDate for before and after
System.out.println("Today is before 01/01/2015? "+today.isBefore(LocalDate.of(2015,1,1)));
//Create LocalDateTime from LocalDate
System.out.println("Current Time="+today.atTime(LocalTime.now()));
//plus and minus operations
System.out.println("10 days after today will be "+today.plusDays(10));
System.out.println("3 weeks after today will be "+today.plusWeeks(3));
System.out.println("20 months after today will be "+today.plusMonths(20));
System.out.println("10 days before today will be "+today.minusDays(10));
System.out.println("3 weeks before today will be "+today.minusWeeks(3));
System.out.println("20 months before today will be "+today.minusMonths(20));
//Temporal adjusters for adjusting the dates
System.out.println("First date of this month= "+today.with(TemporalAdjusters.firstDayOfMonth()));
LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
System.out.println("Last date of this year= "+lastDayOfYear);
Period period = today.until(lastDayOfYear);
System.out.println("Period Format= "+period);
System.out.println("Months remaining in the year= "+period.getMonths());
解析和格式化:將一個日期格式轉(zhuǎn)換為不同的格式,之后再解析一個字符串,得到日期時間對象
//Format examples
LocalDate date = LocalDate.now();
//default format
System.out.println("Default format of LocalDate="+date);
//specific format
System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));
LocalDateTime dateTime = LocalDateTime.now();
//default format
System.out.println("Default format of LocalDateTime="+dateTime);
//specific format
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));
Instant timestamp = Instant.now();
//default format
System.out.println("Default format of Instant="+timestamp);
//Parse examples
LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",
DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
System.out.println("Default format after parsing = "+dt);
舊的日期時間支持轉(zhuǎn)換:
//Date to Instant
Instant timestamp = new Date().toInstant();
//Now we can convert Instant to LocalDateTime or other similar classes
LocalDateTime date = LocalDateTime.ofInstant(timestamp,
ZoneId.of(ZoneId.SHORT_IDS.get("PST")));
System.out.println("Date = "+date);
//Calendar to Instant
Instant time = Calendar.getInstance().toInstant();
System.out.println(time);
//TimeZone to ZoneId
ZoneId defaultZone = TimeZone.getDefault().toZoneId();
System.out.println(defaultZone);
//ZonedDateTime from specific Calendar
ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();
System.out.println(gregorianCalendarDateTime);
//Date API to Legacy classes
Date dt = Date.from(Instant.now());
System.out.println(dt);
TimeZone tz = TimeZone.getTimeZone(defaultZone);
System.out.println(tz);
GregorianCalendar gc = GregorianCalendar.from(gregorianCalendarDateTime);
System.out.println(gc);
public CompletableFuture whenComplete(BiConsumer super T,? super Throwable> action)
public CompletableFuture whenCompleteAsync(BiConsumer super T,? super Throwable> action)
public CompletableFuture whenCompleteAsync(BiConsumer super T,? super Throwable> action, Executor executor)
public CompletableFuture exceptionally(Function fn) 注意:方法不以Async結(jié)尾,意味著Action使用相同的線程執(zhí)行,而Async可能會使用其它的線程去執(zhí)行(如果使用相同的線程池,也可能會被同一個線程選中執(zhí)行)
public class Main {
private static Random rand = new Random();
private static long t = System.currentTimeMillis();
static int getMoreData() {
System.out.println("begin to start compute");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("end to start compute. passed " + (System.currentTimeMillis() - t)/1000 + " seconds");
return rand.nextInt(1000);
}
public static void main(String[] args) throws Exception {
CompletableFuture future = CompletableFuture.supplyAsync(Main::getMoreData);
Future f = future.whenComplete((v, e) -> {
System.out.println(v);
System.out.println(e);
});
System.out.println(f.get());
System.in.read();
}
}
public CompletableFuture acceptEither(CompletionStage extends T> other, Consumer super T> action)
public CompletableFuture acceptEitherAsync(CompletionStage extends T> other, Consumer super T> action)
public CompletableFuture acceptEitherAsync(CompletionStage extends T> other, Consumer super T> action, Executor executor)
public CompletableFuture applyToEither(CompletionStage extends T> other, Function super T,U> fn)
public CompletableFuture applyToEitherAsync(CompletionStage extends T> other, Function super T,U> fn)
public CompletableFuture applyToEitherAsync(CompletionStage extends T> other, Function super T,U> fn, Executor executor) 下面這個例子有時會輸出100,有時候會輸出200,哪個Future先完成就會根據(jù)它的結(jié)果計算。
//ifPresent方法接受lambda表達式作為參數(shù)。
//lambda表達式對Optional的值調(diào)用consumer進行處理。
name.ifPresent((value) -> {
System.out.println("The length of the value is: " + value.length());
});
try {
//orElseThrow與orElse方法類似。與返回默認值不同,
//orElseThrow會拋出lambda表達式或方法生成的異常
empty.orElseThrow(ValueAbsentException::new);
} catch (Throwable ex) {
//輸出: No value present in the Optional instance
System.out.println(ex.getMessage());
}
//filter方法檢查給定的Option值是否滿足某些條件。
//如果滿足則返回同一個Option實例,否則返回空Optional。
Optional longName = name.filter((value) -> value.length() > 6);
System.out.println(longName.orElse("The name is less than 6 characters"));//輸出Sanaulla
//另一個例子是Optional值不滿足filter指定的條件。
Optional anotherName = Optional.of("Sana");
Optional shortName = anotherName.filter((value) -> value.length() > 6);
//輸出:name長度不足6字符
System.out.println(shortName.orElse("The name is less than 6 characters"));