Here you can find the source of reverse(Stream extends T> stream)
Parameter | Description |
---|---|
stream | an ordered stream |
T | the type of the stream elements |
public static <T> Stream<T> reverse(Stream<? extends T> stream)
//package com.java2s; /*/* w ww. ja va 2 s . com*/ * Copyright (C) 2018 Scientific Analysis Instruments Limited <contact@saiman.co.uk> * ______ ___ ___________ * ,'========\ ,'===\ /========== \ * /== \___/== \ ,'==.== \ \__/== \___\/ * /==_/____\__\/,'==__|== | /== / * \========`. ,'========= | /== / * ___`-___)== ,'== \____|== | /== / * /== \__.-==,'== ,' |== '__/== /_ * \======== /== ,' |== ========= \ * \_____\.-\__\/ \__\\________\/ * * This file is part of uk.co.saiman.collections. * * uk.co.saiman.collections is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * uk.co.saiman.collections is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.Iterator; import java.util.List; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class Main { /** * @param stream * an ordered stream * @param <T> * the type of the stream elements * @return a new stream over the elements contained in the given stream in * reverse order */ public static <T> Stream<T> reverse(Stream<? extends T> stream) { List<T> collection = stream.collect(Collectors.toList()); Iterator<T> iterator = new Iterator<T>() { private int index = collection.size(); @Override public boolean hasNext() { return index > 0; } @Override public T next() { return collection.get(--index); } }; return StreamSupport.stream( Spliterators.spliterator(iterator, collection.size(), Spliterator.ORDERED | Spliterator.IMMUTABLE), false); } }