在JDK 9(以及8)以及更高版本中,所有内容都可以作为一个流
在JDK 8中,我們終于可以使用流了,除了您使用的API無法產(chǎn)生流的時(shí)代之外,其他一切都很好。 然后,您最終編寫了一個(gè)包裝器類方法,該方法允許您將迭代器轉(zhuǎn)換為Stream,因?yàn)槟e(cuò)過了流。
public static <T> Stream<T> asStream(Iterator<T> it) {return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it,Spliterator.IMMUTABLE | Spliterator.ORDERED),false); }現(xiàn)在有一些方法可以在迭代和生成的情況下以編程方式生成流,但是這兩種方法都會(huì)生成無限流,而在大多數(shù)情況下,您確實(shí)想將現(xiàn)有接口改編為有限流。
在JDK 9中,通過引入一種新形式的迭代方法很好地解決了該問題,該方法允許您提供一個(gè)謂詞來表示流的結(jié)束。
在下面的示例中,我將使用謂詞,該謂詞將一直持續(xù)到您獲得流的空條目為止,然后由讀者自己來提出謂詞的更多想象力。 在這個(gè)簡(jiǎn)單的示例中,我使用Throwable的getCause方法使我們沿著錯(cuò)誤的鏈接列表移動(dòng)。 請(qǐng)注意,與預(yù)發(fā)布版本相比,這將花費(fèi)很少的代碼。
// 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);第二個(gè)示例將ReferenceQueue轉(zhuǎn)換為Stream,以便我們可以輕松地耗盡其內(nèi)容以根據(jù)需要進(jìn)行處理。 這段代碼有些不同,因?yàn)槿萜髋c要處理的對(duì)象不同,因此我們使用相同的方法提供種子和下一個(gè)值,當(dāng)隊(duì)列為空時(shí),它返回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);第三個(gè)示例顯示了如何在Node樹上行走,請(qǐng)注意,當(dāng)我們工作到葉子的末尾時(shí),嵌套的流迭代器將備份列表。
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);因此,通過進(jìn)行少量的心理操練,就可以將大多數(shù)舊版API轉(zhuǎn)換為干凈的Stream,因此您可以忽略那些討厭的老式循環(huán)。 而且,如果您陷于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
總結(jié)
以上是生活随笔為你收集整理的在JDK 9(以及8)以及更高版本中,所有内容都可以作为一个流的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JMetro 5.2版发布
- 下一篇: linux动态链接库(linux 动态链