java8常用內(nèi)置函數(shù)有哪些

這篇文章將為大家詳細講解有關(guān)java8常用內(nèi)置函數(shù)有哪些,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

為杏花嶺等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及杏花嶺網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為網(wǎng)站制作、成都網(wǎng)站建設(shè)、杏花嶺網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!

常用的函數(shù)接口記錄方便以后翻吧

接口參數(shù)返回類型說明
Predicate<T>Tboolean輸入某個值,輸出boolean 值,用于對某值進行判定
Consumer<T>Tvoid輸入某值,無輸出。用于消費某值
Function<T,R>TR輸入某類型值,輸出另種類型值,用于類型轉(zhuǎn)化等
Supplier<T>NoneT無輸入,輸出某值,用于生產(chǎn)某值
UnaryOperator<T>TT輸入某類型值,輸出同類型值,用于值的同類型轉(zhuǎn)化,如對值進行四則運算等
BinaryOperator<T>(T,T)T輸入兩個某類型值,輸出一個同類型值,用于兩值合并等
Predicates

Predicates是包含一個參數(shù)的布爾值接口。其包括一些缺省方法,組合他們使用可以實現(xiàn)復(fù)雜的業(yè)務(wù)邏輯(如:and, or, negate)。示例代碼如下:

Predicate<String> predicate = (s) -> s.length() > 0;
 
predicate.test("foo");              // true
predicate.negate().test("foo");     // false
 
Predicate<Boolean> nonNull = Objects::nonNull;
Predicate<Boolean> isNull = Objects::isNull;
 
Predicate<String> isEmpty = String::isEmpty;
Predicate<String> isNotEmpty = isEmpty.negate();
Functions

Functions接口接收一個參數(shù)并產(chǎn)生一個結(jié)果。其缺省方法通常被用來鏈接多個功能一起使用 (compose, andThen)。

Function<String, Integer> toInteger = Integer::valueOf;
Function<String, String> backToString = toInteger.andThen(String::valueOf);
 
backToString.apply("123");     // "123"
Suppliers

Suppliers接口生成一個給定類型結(jié)果。和Functions不同,其沒有接收參數(shù)。

Supplier<Person> personSupplier = Person::new;
personSupplier.get();   // new Person
Consumers

Consumers表現(xiàn)執(zhí)行帶有單個輸入?yún)?shù)的操作。

Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
greeter.accept(new Person("Luke", "Skywalker"));
Comparators

Comparators是從java舊版本升級并增加了一些缺省方法。

Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName);
 
Person p1 = new Person("John", "Doe");
Person p2 = new Person("Alice", "Wonderland");
 
comparator.compare(p1, p2);             // > 0
comparator.reversed().compare(p1, p2);  // < 0
Stream 常用方法
創(chuàng)建Stream
  1. 將現(xiàn)有數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)化成Stream
Stream<Integer> s = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> s = Arrays.stream(arr);
Stream<Integer> s = aList.stream();
  1. 通過Stream.generate()方法:
// 這種方法通常表示無限序列
Stream<T> s = Stream.generate(SuppLier<T> s);
// 創(chuàng)建全體自然數(shù)的Stream
class NatualSupplier implements Supplier<BigInteger> {
    BigInteger next = BigInteger.ZERO;
    @Override
    public BigInteger get() {
        next = next.add(BigInteger.ONE);
        return next;
    }
}
  1. 通過其他方法返回
Stream<String> lines = Files.lines(Path.get(filename))
...
map方法

把一種操作運算映射到Stream的每一個元素上,從而完成一個Stream到另一個Stream的轉(zhuǎn)換
map方法接受的對象是Function接口,這個接口是一個函數(shù)式接口:

<R> Stream<R> map(Function<? super T, ? extends R> mapper);


@FunctionalInterface
public interface Function<T, R> {
    // 將T轉(zhuǎn)換為R
    R apply(T t);
}

使用:

// 獲取Stream里每個數(shù)的平方的集合
Stream<Integer> ns = Stream.of(1, 2, 3, 4, 5);
ns.map(n -> n * n).forEach(System.out::println);
flatMap

map方法是一個一對一的映射,每輸入一個數(shù)據(jù)也只會輸出一個值。

flatMap方法是一對多的映射,對每一個元素映射出來的仍舊是一個Stream,然后會將這個子Stream的元素映射到父集合中:

Stream<List<Integer>> inputStream = Stream.of(Arrays.asList(1), Arrays.asList(2, 3), Arrays.asList(4, 5, 6));
List<Integer> integerList = inputStream.flatMap((childList) -> childList.stream()).collect(Collectors.toList());
//將一個“二維數(shù)組”flat為“一維數(shù)組”
integerList.forEach(System.out::println);
filter方法

filter方法用于過濾Stream中的元素,并用符合條件的元素生成一個新的Stream。
filter方法接受的參數(shù)是Predicate接口對象,這個接口是一個函數(shù)式接口:

Stream<T> filter(Predicate<? super T>) predicate;


@FunctionInterface
public interface Predicate<T>   {
    // 判斷元素是否符合條件
    boolean test(T t);
}

使用

// 獲取當前Stream所有偶數(shù)的序列
Stream<Integer> ns = Stream.of(1, 2, 3, 4, 5);
ns.filter(n -> n % 2 == 0).forEach(System.out::println);
limit、skip

limit用于限制獲取多少個結(jié)果,與數(shù)據(jù)庫中的limit作用類似,skip用于排除前多少個結(jié)果。

sorted

sorted函數(shù)需要傳入一個實現(xiàn)Comparator函數(shù)式接口的對象,該接口的抽象方法compare接收兩個參數(shù)并返回一個整型值,作用就是排序,與其他常見排序方法一致。

distinct

distinct用于剔除重復(fù),與數(shù)據(jù)庫中的distinct用法一致。

findFirst

findFirst方法總是返回第一個元素,如果沒有則返回空,它的返回值類型是Optional<T>類型,接觸過swift的同學(xué)應(yīng)該知道,這是一個可選類型,如果有第一個元素則Optional類型中保存的有值,如果沒有第一個元素則該類型為空。

Stream<User> stream = users.stream();
Optional<String> userID = stream.filter(User::isVip).sorted((t1, t2) -> t2.getBalance() - t1.getBalance()).limit(3).map(User::getUserID).findFirst();
userID.ifPresent(uid -> System.out.println("Exists"));
min、max

min可以對整型流求最小值,返回OptionalInt。

max可以對整型流求最大值,返回OptionalInt。

這兩個方法是結(jié)束操作,只能調(diào)用一次。

allMatch、anyMatch、noneMatch

allMatch:Stream中全部元素符合傳入的predicate返回 true

anyMatch:Stream中只要有一個元素符合傳入的predicate返回 true

noneMatch:Stream中沒有一個元素符合傳入的predicate返回 true

reduce方法

reduce方法將一個Stream的每一個元素一次作用于BiFunction,并將結(jié)果合并。
reduce方法接受的方法是BinaryOperator接口對象。

Optional<T> reduce(BinaryOperator<T> accumulator);


@FuncationalInterface
public interface BinaryOperator<T> extends BiFunction<T, T, T> {
    // Bi操作,兩個輸入,一個輸出
    T apply(T t, T u);
}

使用:

// 求當前Stream累乘的結(jié)果
Stream<Integer> ns = Stream.of(1, 2, 3, 4, 5);
int r = ns.reduce( (x, y) -> x * y ).get();
System.out.println(r);

關(guān)于java8常用內(nèi)置函數(shù)有哪些就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

網(wǎng)站名稱:java8常用內(nèi)置函數(shù)有哪些
URL標題:http://www.muchs.cn/article40/iidpeo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站定制開發(fā)、App設(shè)計商城網(wǎng)站、網(wǎng)站收錄網(wǎng)頁設(shè)計公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站建設(shè)網(wǎng)站維護公司