af7845b7c7533381dbf485a075c1cdb5a2d7822b
[deliverable/tracecompass.git] / common / org.eclipse.tracecompass.common.core / src / org / eclipse / tracecompass / common / core / collect / StreamFlattener.java
1 /*******************************************************************************
2 * Copyright (c) 2015 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.collect;
11
12 import java.util.function.Function;
13 import java.util.stream.Stream;
14
15 /**
16 * Generic utility class to "flatten" a data structure using the {@link Stream}
17 * API.
18 *
19 * @author Alexandre Montplaisir
20 *
21 * @param <T>
22 * The type of container, or "node" in the tree
23 * @since 2.0
24 */
25 public class StreamFlattener<T> {
26
27 private final Function<T, Stream<T>> fGetChildrenFunction;
28
29 /**
30 * Constructor
31 *
32 * @param getChildrenFunction
33 * The function to use to get each element's children. Should
34 * return a {@link Stream} of those children.
35 */
36 public StreamFlattener(Function<T, Stream<T>> getChildrenFunction) {
37 fGetChildrenFunction = getChildrenFunction;
38 }
39
40 /**
41 * Do an in-order flattening of the data structure, starting at the given
42 * element (or node).
43 *
44 * @param element
45 * The tree node or similar from which to start
46 * @return A unified Stream of all the children that were found,
47 * recursively.
48 */
49 public Stream<T> flatten(T element) {
50 return Stream.concat(
51 Stream.of(element),
52 fGetChildrenFunction.apply(element).flatMap(this::flatten));
53 }
54 }
This page took 0.033716 seconds and 4 git commands to generate.