jdk 1.8 新特性使用

雖然jdk1.8已經(jīng)是很久以前更新的了硼啤,但是開發(fā)人員對(duì)于1.8的新特性使用可能不是很多过牙,接下來(lái)文章會(huì)說(shuō)一些1.8中用的比較多的功能威彰,趕緊學(xué)起來(lái)

1肝谭,首先用的最多的是stream流的使用

以前我們對(duì)于集合的遍歷是這樣的(舉個(gè)例子)

   for (User user : list) {
            //執(zhí)行便利后的操作
            user.setAge(user.getAge()+1);
        }

stream在jdk1.8中使用

 list.stream().forEach(r->{
            r.setAge(r.getAge()+1);
        });

在1.8中流對(duì)于集合還有很便利的操作

//獲取集合中年齡大于10的用戶
        list.stream().filter(user -> user.getAge()>10).collect(Collectors.toList());
        //根據(jù)用戶的年紀(jì)排序
        list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
        //獲取該集合中年齡最大的用戶
        list.stream().max(Comparator.comparing(User::getAge)).get();
        //將用戶集合中的用戶年齡單獨(dú)取出作為一個(gè)集合(常用與日常開發(fā)中根據(jù)主表id去查詢子表數(shù)據(jù)的業(yè)務(wù)中)
        list.stream().map(User::getAge).collect(Collectors.toList());    
        //將集合按照key是用戶id掘宪,value是用戶本省的map集合
        list.stream().collect(Collectors.toMap(User::getId, Function.identity()));

這些是開發(fā)中常用的一些流的操作,我們?cè)陂_發(fā)中可以組合起來(lái)操作

2攘烛,接下來(lái)是對(duì)于流的操作(輸入流,輸出流)

眾所周知魏滚,我們?cè)谥笆褂幂斎肓鳎敵隽鞯臅r(shí)候每次使用完之后都需要關(guān)閉流坟漱,但是在1.8以后我們還需要關(guān)閉嗎鼠次?不需要了,1.8已經(jīng)幫我們實(shí)現(xiàn)了自動(dòng)關(guān)閉的功能了芋齿,那編碼和以前有什么區(qū)別呢腥寇,1.8又是怎么樣實(shí)現(xiàn)的呢?
那這其中最關(guān)鍵的一個(gè)接口

public interface AutoCloseable {
    /**
     * Closes this resource, relinquishing any underlying resources.
     * This method is invoked automatically on objects managed by the
     * {@code try}-with-resources statement.
     *
     * <p>While this interface method is declared to throw {@code
     * Exception}, implementers are <em>strongly</em> encouraged to
     * declare concrete implementations of the {@code close} method to
     * throw more specific exceptions, or to throw no exception at all
     * if the close operation cannot fail.
     *
     * <p> Cases where the close operation may fail require careful
     * attention by implementers. It is strongly advised to relinquish
     * the underlying resources and to internally <em>mark</em> the
     * resource as closed, prior to throwing the exception. The {@code
     * close} method is unlikely to be invoked more than once and so
     * this ensures that the resources are released in a timely manner.
     * Furthermore it reduces problems that could arise when the resource
     * wraps, or is wrapped, by another resource.
     *
     * <p><em>Implementers of this interface are also strongly advised
     * to not have the {@code close} method throw {@link
     * InterruptedException}.</em>
     *
     * This exception interacts with a thread's interrupted status,
     * and runtime misbehavior is likely to occur if an {@code
     * InterruptedException} is {@linkplain Throwable#addSuppressed
     * suppressed}.
     *
     * More generally, if it would cause problems for an
     * exception to be suppressed, the {@code AutoCloseable.close}
     * method should not throw it.
     *
     * <p>Note that unlike the {@link java.io.Closeable#close close}
     * method of {@link java.io.Closeable}, this {@code close} method
     * is <em>not</em> required to be idempotent.  In other words,
     * calling this {@code close} method more than once may have some
     * visible side effect, unlike {@code Closeable.close} which is
     * required to have no effect if called more than once.
     *
     * However, implementers of this interface are strongly encouraged
     * to make their {@code close} methods idempotent.
     *
     * @throws Exception if this resource cannot be closed
     */
    void close() throws Exception;
}

你去看看jdk中常用的流觅捆,你去看看他們的底層代碼赦役,沒錯(cuò)都繼承/實(shí)現(xiàn)了這個(gè)接口,這個(gè)接口的作用就是幫我們關(guān)閉流栅炒,那我們現(xiàn)在代碼中應(yīng)該怎么寫呢?

 try (FileOutputStream out = new FileOutputStream(new File("C://XXX"));
             FileInputStream in = new FileInputStream(new File("C://XXX"));
        ) {
            in.read();
            out.write(12);
        } catch (IOException e) {
            e.printStackTrace();
        }

這只是舉個(gè)例子掂摔,具體的業(yè)務(wù)邏輯啥的根據(jù)自己功能來(lái)寫,這兩個(gè)流就會(huì)在執(zhí)行完之后自動(dòng)關(guān)閉赢赊,當(dāng)然我們也可以模擬jdk對(duì)于流的操作乙漓,比如我們?cè)谑褂胷edis來(lái)做分布式鎖的時(shí)候我們可以給我們的分布式鎖的工具類實(shí)現(xiàn)AutoCloseable 接口重寫close方法,然后在close方法中完成對(duì)與鎖的釋放释移,根據(jù)自己業(yè)務(wù)需求可自由發(fā)揮使用

3叭披,Optional的使用

Optional可以在很大程度上減少空指針的出現(xiàn),話不多說(shuō)直接上代碼

        ArrayList<User> list = new ArrayList<>();
        //判斷user是否為空如果為空就返回新創(chuàng)建的user
        Optional.ofNullable(user).orElse(new User());
        Optional<User> max = list.stream().max(Comparator.comparing(User::getAge));
        //判斷對(duì)象是否存在
        boolean present = max.isPresent();
        //獲取返回的具體的對(duì)象實(shí)體
        User user1 = max.get();

4秀鞭,時(shí)間類LocalDateTime及其周邊

在jdk1.8以后對(duì)于時(shí)間日歷的操作更加方便了

       Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis() * 1000);
        //獲取年
        calendar.get(Calendar.YEAR);
        //獲取月
        calendar.get(Calendar.MONTH);
        //獲取日
        calendar.get(Calendar.DAY_OF_MONTH);
        //獲取時(shí)
        calendar.get(Calendar.HOUR_OF_DAY);
        //獲取分
        calendar.get(Calendar.MINUTE);
        //獲取秒
        calendar.get(Calendar.MILLISECOND);

現(xiàn)在的操作

        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int monthValue = now.getMonthValue();
        int dayOfMonth = now.getDayOfMonth();
        int dayOfMonth1 = now.getDayOfMonth();
        int hour1 = now.getHour();
        int minute1 = now.getMinute();
        int second = now.getSecond();

更加方便的是對(duì)時(shí)間/日期的操作

        LocalDateTime now = LocalDateTime.now();
        int year = now.getYear();
        int monthValue = now.getMonthValue();
        int dayOfMonth = now.getDayOfMonth();
        int dayOfMonth1 = now.getDayOfMonth();
        int hour1 = now.getHour();
        int minute1 = now.getMinute();
        int second = now.getSecond();
        //添加一天
        LocalDateTime localDateTime = now.plusDays(1);
        //添加一個(gè)小時(shí)
        LocalDateTime localDateTime1 = now.plusHours(1);
        //添加一分鐘;
        LocalDateTime localDateTime2 = now.plusMinutes(1);
        //添加一周
        LocalDateTime localDateTime3 = now.plusWeeks(1);
        //比較兩個(gè)時(shí)間的大小
        int i = localDateTime.compareTo(localDateTime3);
        localDateTime1.isAfter(localDateTime2);
        localDateTime1.isBefore(localDateTime2);
        localDateTime1.isEqual(localDateTime2);
        //此外還提供了更加便捷的創(chuàng)建日歷趋观、時(shí)間的方式
        LocalDateTime localDateTime4 = LocalDateTime.of(2020, 10, 21, 15, 30, 22);
        LocalDate localDate = LocalDate.of(2020, 10, 21);
        LocalTime localTime = LocalTime.of(12, 20, 12, 223);
        //本月的第1天
        localDate.with(TemporalAdjusters.firstDayOfMonth());
        //下月的第1天
        localDate.with(TemporalAdjusters.firstDayOfNextMonth());
        localDate.with(TemporalAdjusters.firstDayOfNextYear());
        //日期轉(zhuǎn)時(shí)間戳ZoneOffset.of("+8")設(shè)置的是時(shí)區(qū)
        Long second1 = localDateTime4.toEpochSecond(ZoneOffset.of("+8"));
        //獲取毫秒數(shù)
        Long milliSecond = localDateTime4.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        //轉(zhuǎn)字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String format = localDateTime4.format(formatter);
        //還有一種創(chuàng)建的時(shí)候帶時(shí)區(qū)的日歷類(方法相似就不做闡述了)
        ZoneId zoneId = ZoneId.of("UTC+1");
        ZonedDateTime zonedDateTime = ZonedDateTime.now(zoneId);

在實(shí)際開發(fā)中靈活運(yùn)用可以有效地提高開發(fā)的效率和代碼質(zhì)量扛禽。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末锋边,一起剝皮案震驚了整個(gè)濱河市皱坛,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌豆巨,老刑警劉巖剩辟,帶你破解...
    沈念sama閱讀 219,366評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異往扔,居然都是意外死亡贩猎,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門萍膛,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)吭服,“玉大人,你說(shuō)我怎么就攤上這事蝗罗⊥ё兀” “怎么了?”我有些...
    開封第一講書人閱讀 165,689評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵串塑,是天一觀的道長(zhǎng)沼琉。 經(jīng)常有香客問我,道長(zhǎng)桩匪,這世上最難降的妖魔是什么打瘪? 我笑而不...
    開封第一講書人閱讀 58,925評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮傻昙,結(jié)果婚禮上闺骚,老公的妹妹穿的比我還像新娘。我一直安慰自己妆档,他們只是感情好僻爽,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著过吻,像睡著了一般进泼。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上纤虽,一...
    開封第一講書人閱讀 51,727評(píng)論 1 305
  • 那天乳绕,我揣著相機(jī)與錄音,去河邊找鬼逼纸。 笑死洋措,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的杰刽。 我是一名探鬼主播菠发,決...
    沈念sama閱讀 40,447評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼王滤,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了滓鸠?” 一聲冷哼從身側(cè)響起雁乡,我...
    開封第一講書人閱讀 39,349評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎糜俗,沒想到半個(gè)月后踱稍,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,820評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡悠抹,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評(píng)論 3 337
  • 正文 我和宋清朗相戀三年珠月,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片楔敌。...
    茶點(diǎn)故事閱讀 40,127評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡啤挎,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出卵凑,到底是詐尸還是另有隱情庆聘,我是刑警寧澤,帶...
    沈念sama閱讀 35,812評(píng)論 5 346
  • 正文 年R本政府宣布氛谜,位于F島的核電站掏觉,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏值漫。R本人自食惡果不足惜澳腹,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望杨何。 院中可真熱鬧酱塔,春花似錦、人聲如沸危虱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)埃跷。三九已至蕊玷,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間弥雹,已是汗流浹背垃帅。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留剪勿,地道東北人贸诚。 一個(gè)月前我還...
    沈念sama閱讀 48,388評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親酱固。 傳聞我的和親對(duì)象是個(gè)殘疾皇子械念,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 16宿命:用概率思維提高你的勝算 以前的我是風(fēng)險(xiǎn)厭惡者,不喜歡去冒險(xiǎn)运悲,但是人生放棄了冒險(xiǎn)龄减,也就放棄了無(wú)數(shù)的可能。 ...
    yichen大刀閱讀 6,054評(píng)論 0 4
  • 公元:2019年11月28日19時(shí)42分農(nóng)歷:二零一九年 十一月 初三日 戌時(shí)干支:己亥乙亥己巳甲戌當(dāng)月節(jié)氣:立冬...
    石放閱讀 6,883評(píng)論 0 2
  • 今天上午陪老媽看病扇苞,下午健身房跑步欺殿,晚上想想今天還沒有斷舍離寄纵,馬上做鳖敷,衣架和旁邊的的布衣架,一看亂亂程拭,又想想自己是...
    影子3623253閱讀 2,914評(píng)論 1 8