JUC基礎(chǔ)之四大函數(shù)式接口 Stream流式計算

函數(shù)式接口:只有一個方法的接口

比如:Runnable接口,forEach接口…….

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

四大原生函數(shù)式接口

Function:范型<T,R> T會作為參數(shù)羔巢,R則是返回值

@FunctionalInterface
public interface Function<T, R> {
    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

舉個例子

public static void main(String[] args)
{
    //函數(shù)式接口
    Function function = new Function<String,Integer>()
    {
        @Override
        public Integer apply(String o)
        {
            return 1;
        }
    };
    System.out.println(function.apply("Y1"));
}
運行結(jié)果:
1

還可以用 Lambda 這么寫

Function functionLambda = (Y1)->{return 1;};
System.out.println(functionLambda.apply("Y1"));

Function functionLambda = Y1->{return 1;};
System.out.println(functionLambda.apply("Y1"));

Predicate(斷定型接口):范型<T> T會作為參數(shù)有咨,根據(jù)邏輯返回布爾值

@FunctionalInterface
public interface Predicate<T> {
    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

舉個例子

public static void main(String[] args)
{
    Predicate predicate = new Predicate<String>()
    {
        //判斷字符串長度是否大于3
        @Override
        public boolean test(String o)
        {
          return o.length()>3;
        }
    };
    System.out.println(predicate.test("Y1"));
}
運行結(jié)果:
false

當(dāng)然也可以用Lambda

Predicate predicate = Y1->{
    if (Y1 instanceof String){
        String o = (String) Y1;
        return  o.length()>3;
    }else {
        return false;
    }
};
System.out.println(predicate.test("Y111"));
運行結(jié)果:
true

或者更加簡化

Predicate<String> predicate = Y1->{return Y1.length()>3;};
System.out.println(predicate.test("Y111"));

Consumer(消費型接口) 范型<T> T會作為參數(shù)乖订,沒有返回值

@FunctionalInterface
public interface Consumer<T> {
    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

舉個例子

public static void main(String[] args)
{
    Consumer<String> consumer = new Consumer<String>()
    {
        @Override
        public void accept(String o)
        {
            System.out.println(o);
        }
    };
    consumer.accept("Y1");
}
運行結(jié)果:
Y1

Lambda

Consumer<String> consumer = Y1->{ System.out.println(Y1); };
consumer.accept("Y1”);
運行結(jié)果:
Y1

Supplier(供給型接口) 沒有參數(shù)只有返回值

@FunctionalInterface
public interface Supplier<T> {
    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

舉個例子

public static void main(String[] args)
{
    Supplier<String> supplier = new Supplier<String>()
    {
        @Override
        public String get()
        {
            return "Y1";
        }
    };
    System.out.println(supplier.get());
}
運行結(jié)果:
Y1

Lambda

Supplier<String> supplier = ()->{return "Y1";};
System.out.println(supplier.get());
運行結(jié)果:
Y1

函數(shù)式接口簡化類編程模型酥馍,框架底層應(yīng)用比較多,下面的流式計算會用到很多函數(shù)式接口

Stream流式計算

看一個例子:

public class StreamDemo
{
    public static void main(String[] args)
    {
        /*
        要求用一行代碼實現(xiàn)
        現(xiàn)在有6個用戶
        篩選:
        ID 必須是偶數(shù)
        年齡必須大于3歲
        用戶名轉(zhuǎn)為大寫字母
        用戶名字母倒著排序
        只輸出一個用戶的名字
         */
        User user1 = new User(1,"a",1);
        User user2 = new User(2,"b",2);
        User user3 = new User(3,"c",3);
        User user4 = new User(4,"d",4);
        User user5 = new User(5,"e",5);
        User user6 = new User(6,"f",6);
    }
}

這時候就要用到鏈式編程坦喘,lambda表達式,函數(shù)式接口饺饭,還有Stream流式計算

//集合負責(zé)存儲
List<User> users = Arrays.asList(user1, user2, user3, user4, user5,user6);
//計算交給stream流
users.stream()
        .filter(user -> {return  user.getId()%2==0;})  // id偶數(shù)
        .filter(user -> {return  user.getAge()>3;})  //年齡大于三
        .map(user -> {return user.getName().toUpperCase();})  //名字變成大大寫
        .sorted((u1,u2) -> {return  u2.compareTo(u1);})  //倒排序
        .limit(1)  //輸出一個用戶
        .forEach(System.out::print);
運行結(jié)果
F
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末渤早,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子瘫俊,更是在濱河造成了極大的恐慌,老刑警劉巖悴灵,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件扛芽,死亡現(xiàn)場離奇詭異,居然都是意外死亡积瞒,警方通過查閱死者的電腦和手機川尖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來茫孔,“玉大人叮喳,你說我怎么就攤上這事$直矗” “怎么了馍悟?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長剩晴。 經(jīng)常有香客問我锣咒,道長,這世上最難降的妖魔是什么赞弥? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任毅整,我火速辦了婚禮,結(jié)果婚禮上绽左,老公的妹妹穿的比我還像新娘悼嫉。我一直安慰自己,他們只是感情好拼窥,可當(dāng)我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布戏蔑。 她就那樣靜靜地躺著,像睡著了一般闯团。 火紅的嫁衣襯著肌膚如雪辛臊。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天房交,我揣著相機與錄音彻舰,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛刃唤,可吹牛的內(nèi)容都是我干的隔心。 我是一名探鬼主播,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼尚胞,長吁一口氣:“原來是場噩夢啊……” “哼硬霍!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起笼裳,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤唯卖,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后躬柬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體拜轨,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年允青,在試婚紗的時候發(fā)現(xiàn)自己被綠了橄碾。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡颠锉,死狀恐怖法牲,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情琼掠,我是刑警寧澤拒垃,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站眉枕,受9級特大地震影響恶复,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜速挑,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一谤牡、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧姥宝,春花似錦翅萤、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至碳蛋,卻和暖如春胚泌,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背肃弟。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工玷室, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留零蓉,地道東北人。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓穷缤,卻偏偏與公主長得像敌蜂,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子津肛,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,592評論 2 353