jdk11换jdk8版本_在JDK 9(以及8)以及更高版本中,所有内容都可以作为一个流
jdk11換jdk8版本
在JDK 8中,我們終于可以使用流了,除了您使用的API無法產生流的時代之外,其他一切都很好。 然后,您最終編寫了一個包裝器類方法,該方法允許您將迭代器轉換為Stream,因為您錯過了流。
public static <T> Stream<T> asStream(Iterator<T> it) {return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it,Spliterator.IMMUTABLE | Spliterator.ORDERED),false); }現在有一些方法可以在迭代和生成的情況下以編程方式生成流,但是這兩種方法都會生成無限流,而在大多數情況下,您確實想將現有接口改編為有限流。
在JDK 9中,通過引入一種新形式的迭代方法很好地解決了該問題,該方法允許您提供一個謂詞來表示流的結束。
在下面的示例中,我將使用謂詞,該謂詞將一直持續到您獲得流的空條目為止,我將留給讀者以提供更多富于想象力的謂詞用法。 在這個簡單的示例中,我使用Throwable的getCause方法來使我們沿著錯誤的鏈接列表移動。 請注意,與預發布版本相比,這將花費很少的代碼。
// Simple linked list // Exception e = new Exception("one"); Exception e2 = new Exception("two",e); Exception e3 = new Exception("three", e2);Stream.iterate(e3, Objects::nonNull, Throwable::getCause)// Output the messages in turn.map(Throwable::getMessage).forEach(System.out::println);第二個示例將ReferenceQueue轉換為Stream,以便我們可以輕松地耗盡其內容以根據需要進行處理。 這段代碼有些不同,因為容器與要處理的對象不同,因此我們使用相同的方法提供種子和下一個值。當隊列為空時,此方法返回null。
ReferenceQueue<Thing> queue = new ReferenceQueue<>();// Make some things and then collect them WeakReference one = new WeakReference<Thing>(new Thing(), queue); WeakReference two = new WeakReference<Thing>(new Thing(), queue); System.gc(); System.gc(); System.gc(); System.gc(); System.gc();Stream.<Reference<? extends Thing>>iterate(queue.poll(), Objects::nonNull, v -> queue.poll()).forEach(System.out::println);第三個示例顯示了在Node樹上的遍歷,請注意,當我們工作到葉子的末尾時,嵌套的流迭代器將備份列表。
Node root = doc.getDocumentElement();Stream.iterate(root,Objects::nonNull,v -> {if (v.getFirstChild()!=null) {return v.getFirstChild();}if (v.getNextSibling()!=null) {return v.getNextSibling();}return Stream.iterate(v, Objects::nonNull, Node::getParentNode).filter(node -> node.getNextSibling()!=null).map(Node::getNextSibling).findFirst().orElse(null);}).map(Node::getNodeName).forEach(System.out::println);因此,通過進行少量的心理操練,就可以將大多數舊版API轉換為干凈的Stream,從而可以忽略那些討厭的老式循環。 而且,如果您陷于JDK 8中,那么很容易使用之前的asStream來組合類似的功能:
public static<T> Stream<T> iterateFinite(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) {return asStream(new Iterator<>() {T current = seed;@Overridepublic boolean hasNext() {return hasNext.test(current);}@Overridepublic T next() {if (current == null) {throw new NoSuchElementException();}try {return current;} finally {current = next.apply(current);}}}); }翻譯自: https://www.javacodegeeks.com/2018/12/jdk-9-everything-can-stream.html
jdk11換jdk8版本
總結
以上是生活随笔為你收集整理的jdk11换jdk8版本_在JDK 9(以及8)以及更高版本中,所有内容都可以作为一个流的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么设置vps用ip访问(vps如何搭建
- 下一篇: java客户端api文档_Java 11