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.Collectors;
009import java.util.stream.IntStream;
010import java.util.stream.Stream;
011import java.util.stream.StreamSupport;
012
013/**
014 * Utility methods for streams.
015 * @author Michael Zangl
016 */
017public final class StreamUtils {
018
019    /**
020     * Utility class
021     */
022    private StreamUtils() {
023        // Hide default constructor for utility classes
024    }
025
026    /**
027     * Returns a sequential {@code Stream} with the iterable as its source.
028     * @param <T> The element type to iterate over
029     * @param iterable The iterable
030     * @return The stream of for that iterable.
031     * @since 10718
032     */
033    public static <T> Stream<T> toStream(Iterable<T> iterable) {
034        return StreamSupport.stream(iterable.spliterator(), false);
035    }
036
037    /**
038     * Creates a stream iterating the list in reversed order
039     * @param list the list to iterate over
040     * @param <T> the type of elements in the list
041     * @return a stream iterating the list in reversed order
042     * @since 15732
043     */
044    public static <T> Stream<T> reversedStream(List<T> list) {
045        Objects.requireNonNull(list, "list");
046        final int size = list.size();
047        return IntStream.range(0, size).mapToObj(i -> list.get(size - i - 1));
048    }
049
050    /**
051     * Creates a new Collector that collects the items and returns them as HTML unordered list.
052     * @return The collector.
053     * @since 10638
054     */
055    public static Collector<String, ?, String> toHtmlList() {
056        return Collector.of(
057                () -> new StringJoiner("</li><li>", "<ul><li>", "</li></ul>").setEmptyValue("<ul></ul>"),
058                StringJoiner::add, StringJoiner::merge, StringJoiner::toString
059        );
060    }
061
062    /**
063     * Creates a new Collector that collects the items in an unmodifiable list
064     * @param <T> the type of the input elements
065     * @return a new Collector that collects the items in an unmodifiable list
066     * @see Utils#toUnmodifiableList
067     * @since 16436
068     */
069    public static <T> Collector<T, ?, List<T>> toUnmodifiableList() {
070        // Java 10: use java.util.stream.Collectors.toUnmodifiableList
071        return Collectors.collectingAndThen(Collectors.toList(), Utils::toUnmodifiableList);
072    }
073}