Created
November 18, 2016 08:45
-
-
Save sermojohn/d2e6df4f98645a7f9a32656e2fe54e59 to your computer and use it in GitHub Desktop.
Java Streams for hierarchical object traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package concepts; | |
import java.util.Collection; | |
import java.util.LinkedList; | |
import java.util.UUID; | |
import java.util.stream.Stream; | |
public class ItemProcessor { | |
public static void main(String[] args) { | |
generateStreamOf(5) | |
.map(Item::new) | |
.peek(p -> generateStreamOf(2).map(Item::new).forEach(p::addChild)) | |
.forEach(System.out::println); | |
} | |
private static Stream<Item> generateItems(int n) { | |
return generateStreamOf(n) | |
.map(Item::new); | |
} | |
private static Stream<String> generateStreamOf(int n) { | |
return Stream.generate(() -> UUID.randomUUID().toString()) | |
.limit(n); | |
} | |
private static class Item { | |
final private String name; | |
private Collection<Item> children = new LinkedList<>(); | |
public Item(String name) { | |
this.name = name; | |
} | |
public void addChild(Item child) { | |
this.children.add(child); | |
} | |
@Override | |
public String toString() { | |
return "Item{" + "name='" + name + '\'' | |
+ (children.size() > 0 ? ", children=" + children : "") | |
+ '}'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment