JDK8至JDK 11 新增常用API总结<一>

1.Optional

新增:
stream()
ifPresentOrElse​(Consumer<? super T> action, Runnable emptyAction)
or​(Supplier<? extends Optional<? extends T>> supplier)
版本: 9
orElseThrow()
版本: 10
isEmpty()
版本: 11

    import com.lenovo.mykafka.domain.User;
	import lombok.extern.slf4j.Slf4j;
	import org.assertj.core.util.Lists;
	import org.junit.jupiter.api.Test;
	import org.springframework.boot.test.context.SpringBootTest;
	import org.springframework.util.ObjectUtils;
	
	import java.util.Arrays;
	import java.util.List;
	import java.util.Optional;
	import java.util.function.Supplier;
	import java.util.stream.IntStream;
	import java.util.stream.Stream;
    private void tstOptional() {
        List<String> list = Arrays.asList("a", "b", "c");
        /**
         * 如果list集合不为空,将list集合赋值给newList;如果list集合为空创建一个空对象集合赋值给newList,保证list集合永远不为空,也就避免了空指针异常。
         */
        List<String> newList = Optional.ofNullable(list).orElse(Lists.newArrayList());// ★★★★★ 正确写法
        Optional<List<String>> optional = Optional.of(newList);
        boolean empty = optional.isEmpty();
        System.out.println(empty);// false
        /*字符串判断是否是空,不可用OPtional*/
        String s = "";
        System.out.println(ObjectUtils.isEmpty(s));// true
        String s1 = null;
        System.out.println(ObjectUtils.isEmpty(s1));// true

        Optional<String> stringOptional = Optional.ofNullable(s);
        System.out.println(stringOptional.isEmpty());// false ★★★★★ 字符串判空不可用Optioal, ""空字符判定为非空
        Optional<String> stringOptional1 = Optional.ofNullable(s1);
        System.out.println(stringOptional1.isEmpty());// true

        // TODO 深入使用Ooptional.ofNullable().orElse();
        User user = User.builder()
                .name("小黑")
                .build();
        // ★★★★★ 注意:不管ofNullable 中是否为null,orElse中的 m2()方法总是会被调用到,故m2()中不能有其他增删改数据库的操作
        user.setName(Optional.ofNullable(user.getName()).orElse(m2()));

        // 如果orElse()中的计算或其他处理业务很多时,推荐使用orElseGet()
        // ★★★★★ 注意:ofNullable 中不为null,orElseGet中的 m2()方法也会被调用到,故m2()中能有其他增删改数据库的操作
        user.setName(Optional.ofNullable(user.getName()).orElseGet(m3()));
        // ★★★★★ 注意:ofNullable 中不为null, orElseGet中lambda表达式条件下:orElseGet中的 m2()方法不会被调用到,故m2()中能有其他增删改数据库的操作
        user.setName(Optional.ofNullable(user.getName()).orElseGet(()-> String.valueOf(m3())));
        System.out.println(user.toString());

        User userNUll = null;
        /**
         * java.util.NoSuchElementException: No value present
         * 	at java.base/java.util.Optional.orElseThrow
         */
        //User user1 = Optional.ofNullable(userNUll).orElseThrow();
        //System.out.println(user1);

        /**
         * java.lang.NullPointerException
         * 	at com.lenovo.mykafka.jdk.Test8To11.lambda$test$1(Test8To11.java:72)
         * 	at java.base/java.util.Optional.orElseThrow(
         */
        /*Optional.ofNullable(userNUll).orElseThrow(()->{
            throw new NullPointerException();
        });*/
        Optional<Object> empty1 = Optional.empty();
        System.out.println(empty1);// Optional.empty
    }

2.CompletableFuture

新增:
completeOnTimeout​(T value, long timeout, TimeUnit unit)
newIncompleteFuture()
defaultExecutor()
copy()
minimalCompletionStage()
completeAsync​(Supplier<? extends T> supplier, Executor executor)
orTimeout​(long timeout, TimeUnit unit)
delayedExecutor​(long delay, TimeUnit unit, Executor executor)
delayedExecutor​(long delay, TimeUnit unit)
completedStage​(U value)
failedFuture​(Throwable ex)
failedStage​(Throwable ex)
版本: 9

3.Stream

新增:
takeWhile​(Predicate<? super T> predicate)
dropWhile​(Predicate<? super T> predicate)
ofNullable​(T t)
iterate​(T seed, Predicate<? super T> hasNext, UnaryOperator next)
版本: 9

集合相关===============****TIPS:
jdk11中,list, set, map 的of(), CopyOf(),返回的都是不可变集合;以List为例:
List.of 内部是创建一个的 immutable collections。不可变集合。所以不可以增删改元素。
List.of() 和 List.copyOf() 都是创建的不可变集合

    private void tstListOfMethod() {
        List<Integer> arrayList = Lists.newArrayList(1, 2, 3, 4);
        System.out.println(arrayList.toString());
        arrayList.add(5);
        System.out.println(arrayList.toString());
        /*List<Integer> integers2 = List.copyOf(arrayList);*/
        List<Integer> integers2 = new ArrayList<>(List.copyOf(arrayList));
        integers2.add(6);
        System.out.println(integers2.toString());


        System.out.println("++++++++++++++++++++++++++++++++++++");
        List<Integer> integers = List.of(1, 2, 3);
        List<Integer> integers0 = new ArrayList<>(List.of(1, 2, 3));// 这样可以使得创建的对象,为可变集合
        List<Integer> integers1 = List.copyOf(integers);
        System.out.println(integers == integers1);
        System.out.println(integers0.add(4));
        System.out.println(integers0.toString());
        //System.out.println(integers.add(4));
        /**
         * java.lang.UnsupportedOperationException
         * at com.lenovo.mykafka.jdk.Test8To11.test(Test8To11.java:33)
         */

        //System.out.println(integers1.add(5));
        /**
         * java.lang.UnsupportedOperationException
         */}

4.Map

新增:
of() 系列方法
entry​(K k, V v)
版本: 9
copyOf​(Map<? extends K,​? extends V> map)
版本: 10

5.List

新增:
of() 系列方法
版本: 9
copyOf​(Collection<? extends E> coll)
版本: 10

6.Set

新增:
of() 系列方法
版本: 9
copyOf​(Collection<? extends E> coll)
版本: 10

7.LocalDate

新增:
datesUntil​(LocalDate endExclusive)
datesUntil​(LocalDate endExclusive, Period step)
toEpochSecond​(LocalTime time, ZoneOffset offset)
版本: 9

8.Locale

新增:
getISOCountries​(Locale.IsoCountryCode type)
版本: 9

9.String

新增:
strip()
stripLeading()
stripTrailing()
isBlank()
lines()
repeat​(int count)
版本: 11
chars()
codePoints()
版本: 9
jdk11新增:

    import com.lenovo.mykafka.domain.User;
	import lombok.extern.slf4j.Slf4j;
	import org.assertj.core.util.Lists;
	import org.junit.jupiter.api.Test;
	import org.springframework.boot.test.context.SpringBootTest;
	import org.springframework.util.ObjectUtils;
	
	import java.util.Arrays;
	import java.util.List;
	import java.util.Optional;
	import java.util.function.Supplier;
	import java.util.stream.IntStream;
	import java.util.stream.Stream;
    private void tstJDK11Str() {
        /**
         * 三种空格unicode(\u00A0,\u0020,\u3000)表示的区别
         * 1.不间断空格\u00A0,主要用在office中,让一个单词在结尾处不会换行显示,快捷键ctrl+shift+space ;
         * 2.半角空格(英文符号)\u0020,代码中常用的;
         * 3.全角空格(中文符号)\u3000,中文文章中使用;
         *
         * 全角和半角
         * 在输入法中存在全角和半角字符的概念,比如说“逗号”存在“全角逗号和半角逗号”,体现在Unicode中就是两个不同的码位。
         * 通常全角字符占两个半角字符的位置,中文输入法下的“中文字符和标点符号”为全角字符,但空白字符默认仍然是半角字符,
         * 所以除非刻意使用全角空白符,否则一般都是半角空白符。
         * 全角半角和中文英文输入法没关系,中文下可以用半角,英文下也可以用全角。
         *
         * 当然中文字符必须是全角,不然放不下;英文可以用全角,如f占两个字符
         */
        String s1 = "\u0020woshi\u0020zhoongguoren\u0020你好\u0020";// 半角空格
        String s2 = "\u3000woshi\u3000zhoongguoren\u3000你好\u3000";// 全角空格
        System.out.println(s1 +" "+ s1.length());// woshi zhoongguoren 你好  23
        System.out.println(s2 +" "+ s2.length());//  woshi zhoongguoren 你好  23

        boolean blank = s1.isBlank();
        System.out.println(blank);// false
        boolean empty = s1.isEmpty();
        System.out.println(empty);// false

        // String.trim() 可以去除字符串前后的“半角”空白字符
        String trim1 = s1.trim();
        String trim2 = s2.trim();
        System.out.println(trim1 +" "+ trim1.length());// woshi zhoongguoren 你好 21
        System.out.println(trim2 +" "+ trim2.length());//  woshi zhoongguoren 你好  23
        // String.strip() 可以去除字符串前后的“全角和半角”空白字符 JDK11中引入String.strip()
        String strip1 = s1.strip();// 去除首部尾部空白
        String strip2 = s2.strip();
        System.out.println(strip1 +" "+ strip1.length());// woshi zhoongguoren 你好 21
        System.out.println(strip2 +" "+ strip2.length());// woshi zhoongguoren 你好 21

        String stripTrailing = s1.stripTrailing();// 去除尾部空白
        System.out.println(stripTrailing);//  woshi zhoongguoren 你好
        String stripLeading = s1.stripLeading();// 去除首部空白
        System.out.println(stripLeading);//
        String repeat = s1.repeat(3);// 复制几遍字符串
        System.out.println(repeat);//  woshi zhoongguoren 你好  woshi zhoongguoren 你好  woshi zhoongguoren 你好
        Stream<String> lines = s1.lines();// 行数统计
        long count = lines.count();
        System.out.println(count);// 1
    }

jdk9:

    private void tstCodePoints() {
        /**
         * IntStream类的codePoints()方法用于从给定序列中获取代码点值流。它返回作为参数传递的字符的ASCII值
         */
        String s = "woshsif ";
        IntStream intStream = s.chars();
        intStream.forEach(System.out::println);
        /**
         * 119
         * 111
         * 115
         * 104
         * 115
         * 105
         * 102
         * 32
         */

        s.chars().map(i->(char)i)
                .forEach(System.out::println);
        /**
         * 119
         * 111
         * 115
         * 104
         * 115
         * 105
         * 102
         * 32
         */

        IntStream codePoints = s.codePoints();
        codePoints.forEach(System.out::println);
        /**
         * 119
         * 111
         * 115
         * 104
         * 115
         * 105
         * 102
         * 32
         */}

10.HttpClient

新增类
版本: 11

11.InputStream

新增:
nullInputStream()
readNBytes​(int len) throws IOException
版本: 11
readAllBytes() throws IOException
readNBytes​(byte[] b, int off, int len) throws IOException
transferTo​(OutputStream out) throws IOException
版本: 9

12.OutputStream

新增:
nullOutputStream()
版本: 11

13.ByteArrayOutputStream

新增:
writeBytes​(byte[] b)
版本: 11
toString​(Charset charset)
版本: 10

14.Selector

新增:
select​(Consumer action, long timeout) throws IOException
select​(Consumer action) throws IOException
selectNow​(Consumer action) throws IOException
版本: 11

15.Objects

新增:
requireNonNullElse​(T obj, T defaultObj)
requireNonNullElseGet​(T obj, Supplier<? extends T> supplier)
checkIndex​(int index, int length)
checkFromToIndex​(int fromIndex, int toIndex, int length)
checkFromIndexSize​(int fromIndex, int size, int length)
版本: 9

16.Path

新增:
of​(String first, String… more)
of​(URI uri)
版本: 11

17.Files

新增:
readString​(Path path) throws IOException
readString​(Path path, Charset cs) throws IOException
writeString​(Path path, CharSequence csq, OpenOption… options) throws IOException
writeString​(Path path, CharSequence csq, Charset cs, OpenOption… options) throws IOException
版本: 11

18.Socket

新增:
setOption​(SocketOption name, T value) throws IOException
getOption​(SocketOption name) throws IOException
supportedOptions()
版本: 9

19.HttpURLConnection

新增:
setAuthenticator​(Authenticator auth)
版本: 9

20.URLClassLoader

新增:
URLClassLoader​(String name, URL[] urls, ClassLoader parent)
URLClassLoader​(String name, URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory)
版本: 9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值