001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.tools;
003
004import java.util.List;
005import java.util.Objects;
006import java.util.StringJoiner;
007import java.util.stream.Collector;
008import java.util.stream.IntStream;
009import java.util.stream.Stream;
010import java.util.stream.StreamSupport;
011
012/**
013 * Utility methods for streams.
014 * @author Michael Zangl
015 */
016public final class StreamUtils {
017
018    /**
019     * Utility class
020     */
021    private StreamUtils() {
022        // Hide default constructor for utility classes
023    }
024
025    /**
026     * Returns a sequential {@code Stream} with the iterable as its source.
027     * @param <T> The element type to iterate over
028     * @param iterable The iterable
029     * @return The stream of for that iterable.
030     * @since 10718
031     */
032    public static <T> Stream<T> toStream(Iterable<T> iterable) {
033        return StreamSupport.stream(iterable.spliterator(), false);
034    }
035
036    /**
037     * Creqates a stream iterating the list in reversed order
038     * @param list the list to iterate over
039     * @param <T> the type of elements in the list
040     * @return a stream iterating the list in reversed order
041     * @since 15732
042     */
043    public static <T> Stream<T> reversedStream(List<T> list) {
044        Objects.requireNonNull(list, "list");
045        final int size = list.size();
046        return IntStream.range(0, size).mapToObj(i -> list.get(size - i - 1));
047    }
048
049    /**
050     * Creates a new Collector that collects the items and returns them as HTML unordered list.
051     * @return The collector.
052     * @since 10638
053     */
054    public static Collector<String, ?, String> toHtmlList() {
055        return Collector.of(
056                () -> new StringJoiner("</li><li>", "<ul><li>", "</li></ul>").setEmptyValue("<ul></ul>"),
057                StringJoiner::add, StringJoiner::merge, StringJoiner::toString
058        );
059    }
060}