Commit | Line | Data |
---|---|---|
648903b9 AM |
1 | /******************************************************************************* |
2 | * Copyright (c) 2016 EfficiOS Inc., Alexandre Montplaisir | |
3 | * | |
4 | * All rights reserved. This program and the accompanying materials | |
5 | * are made available under the terms of the Eclipse Public License v1.0 | |
6 | * which accompanies this distribution, and is available at | |
7 | * http://www.eclipse.org/legal/epl-v10.html | |
8 | *******************************************************************************/ | |
9 | ||
10 | package org.eclipse.tracecompass.common.core; | |
11 | ||
12 | import static org.eclipse.tracecompass.common.core.NonNullUtils.checkNotNull; | |
13 | ||
14 | import java.util.function.Function; | |
15 | import java.util.stream.Stream; | |
16 | import java.util.stream.StreamSupport; | |
17 | ||
18 | /** | |
19 | * Common utilities for {@link Stream}. | |
20 | * | |
21 | * @author Alexandre Montplaisir | |
22 | * @since 2.0 | |
23 | */ | |
24 | public final class StreamUtils { | |
25 | ||
26 | private StreamUtils() {} | |
27 | ||
28 | /** | |
29 | * Get a sequential {@link Stream} from an {@link Iterable}. | |
30 | * | |
31 | * @param iterable | |
32 | * Any iterable | |
33 | * @return The stream on the elements of the iterable | |
34 | */ | |
35 | public static <T> Stream<T> getStream(Iterable<T> iterable) { | |
36 | return StreamSupport.stream(iterable.spliterator(), false); | |
37 | } | |
38 | ||
39 | /** | |
40 | * Generic utility class to "flatten" a data structure using the | |
41 | * {@link Stream} API. | |
42 | * | |
43 | * @param <T> | |
44 | * The type of container, or "node" in the tree | |
45 | */ | |
46 | public static class StreamFlattener<T> { | |
47 | ||
48 | private final Function<T, Stream<T>> fGetChildrenFunction; | |
49 | ||
50 | /** | |
51 | * Constructor | |
52 | * | |
53 | * @param getChildrenFunction | |
54 | * The function to use to get each element's children. Should | |
55 | * return a {@link Stream} of those children. | |
56 | */ | |
57 | public StreamFlattener(Function<T, Stream<T>> getChildrenFunction) { | |
58 | fGetChildrenFunction = getChildrenFunction; | |
59 | } | |
60 | ||
61 | /** | |
62 | * Do an in-order flattening of the data structure, starting at the given | |
63 | * element (or node). | |
64 | * | |
65 | * @param element | |
66 | * The tree node or similar from which to start | |
67 | * @return A unified Stream of all the children that were found, | |
68 | * recursively. | |
69 | */ | |
70 | public Stream<T> flatten(T element) { | |
71 | Stream<T> ret = Stream.concat( | |
72 | Stream.of(element), | |
73 | fGetChildrenFunction.apply(element).flatMap(this::flatten)); | |
74 | return checkNotNull(ret); | |
75 | } | |
76 | } | |
77 | } |