1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.tools;
|
---|
3 |
|
---|
4 | import java.util.List;
|
---|
5 | import java.util.Objects;
|
---|
6 | import java.util.StringJoiner;
|
---|
7 | import java.util.stream.Collector;
|
---|
8 | import java.util.stream.IntStream;
|
---|
9 | import java.util.stream.Stream;
|
---|
10 | import java.util.stream.StreamSupport;
|
---|
11 |
|
---|
12 | /**
|
---|
13 | * Utility methods for streams.
|
---|
14 | * @author Michael Zangl
|
---|
15 | */
|
---|
16 | public final class StreamUtils {
|
---|
17 |
|
---|
18 | /**
|
---|
19 | * Utility class
|
---|
20 | */
|
---|
21 | private StreamUtils() {
|
---|
22 | // Hide default constructor for utility classes
|
---|
23 | }
|
---|
24 |
|
---|
25 | /**
|
---|
26 | * Returns a sequential {@code Stream} with the iterable as its source.
|
---|
27 | * @param <T> The element type to iterate over
|
---|
28 | * @param iterable The iterable
|
---|
29 | * @return The stream of for that iterable.
|
---|
30 | * @since 10718
|
---|
31 | */
|
---|
32 | public static <T> Stream<T> toStream(Iterable<T> iterable) {
|
---|
33 | return StreamSupport.stream(iterable.spliterator(), false);
|
---|
34 | }
|
---|
35 |
|
---|
36 | /**
|
---|
37 | * Creqates a stream iterating the list in reversed order
|
---|
38 | * @param list the list to iterate over
|
---|
39 | * @param <T> the type of elements in the list
|
---|
40 | * @return a stream iterating the list in reversed order
|
---|
41 | * @since 15732
|
---|
42 | */
|
---|
43 | public static <T> Stream<T> reversedStream(List<T> list) {
|
---|
44 | Objects.requireNonNull(list, "list");
|
---|
45 | final int size = list.size();
|
---|
46 | return IntStream.range(0, size).mapToObj(i -> list.get(size - i - 1));
|
---|
47 | }
|
---|
48 |
|
---|
49 | /**
|
---|
50 | * Creates a new Collector that collects the items and returns them as HTML unordered list.
|
---|
51 | * @return The collector.
|
---|
52 | * @since 10638
|
---|
53 | */
|
---|
54 | public static Collector<String, ?, String> toHtmlList() {
|
---|
55 | return Collector.of(
|
---|
56 | () -> new StringJoiner("</li><li>", "<ul><li>", "</li></ul>").setEmptyValue("<ul></ul>"),
|
---|
57 | StringJoiner::add, StringJoiner::merge, StringJoiner::toString
|
---|
58 | );
|
---|
59 | }
|
---|
60 | }
|
---|