Commit | Line | Data |
---|---|---|
40854318 AM |
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.tests.collect; | |
11 | ||
12 | import static org.junit.Assert.assertEquals; | |
13 | ||
14 | import java.util.Arrays; | |
15 | import java.util.List; | |
16 | import java.util.stream.Collectors; | |
17 | ||
18 | import org.eclipse.tracecompass.common.core.collect.StreamFlattener; | |
19 | import org.junit.Test; | |
20 | ||
21 | /** | |
22 | * Test for {@link StreamFlattener}. | |
23 | * | |
24 | * @author Alexandre Montplaisir | |
25 | */ | |
26 | public class StreamFlattenerTest { | |
27 | ||
28 | /** | |
29 | * Test flattening a tree. | |
30 | * | |
31 | * Each node has a String value, and they will be organized as: | |
32 | * | |
33 | * <pre> | |
34 | * A | |
35 | * / \ | |
36 | * B C | |
37 | * /| |\ | |
38 | * D E F G | |
39 | * </pre> | |
40 | * | |
41 | * In-order, depth-first visiting should give the following sequence:<br> | |
42 | * A -> B -> D -> E -> C -> F -> G | |
43 | */ | |
44 | @Test | |
45 | public void testFlattenTree() { | |
46 | /* Prepare the tree */ | |
47 | TreeNode nodeD = new TreeNode(new TreeNode[0], "D"); | |
48 | TreeNode nodeE = new TreeNode(new TreeNode[0], "E"); | |
49 | TreeNode nodeF = new TreeNode(new TreeNode[0], "F"); | |
50 | TreeNode nodeG = new TreeNode(new TreeNode[0], "G"); | |
51 | TreeNode nodeB = new TreeNode(new TreeNode[] {nodeD, nodeE}, "B"); | |
52 | TreeNode nodeC = new TreeNode(new TreeNode[] {nodeF, nodeG}, "C"); | |
53 | TreeNode nodeA = new TreeNode(new TreeNode[] {nodeB, nodeC}, "A"); | |
54 | ||
55 | /* Run the test */ | |
56 | StreamFlattener<TreeNode> sf = new StreamFlattener<>(node -> Arrays.stream(node.getChildren())); | |
57 | ||
58 | List<String> expected = Arrays.asList("A", "B", "D", "E", "C", "F", "G"); | |
59 | List<String> results = sf.flatten(nodeA).map(TreeNode::getValue).collect(Collectors.toList()); | |
60 | ||
61 | assertEquals(expected, results); | |
62 | } | |
63 | ||
64 | private static class TreeNode { | |
65 | ||
66 | private final TreeNode[] children; | |
67 | private final String value; | |
68 | ||
69 | public TreeNode(TreeNode[] children, String value) { | |
70 | this.children = children; | |
71 | this.value = value; | |
72 | } | |
73 | ||
74 | public TreeNode[] getChildren() { | |
75 | return children; | |
76 | } | |
77 | ||
78 | public String getValue() { | |
79 | return value; | |
80 | } | |
81 | } | |
82 | } |