fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.stream.*;
  5. import java.lang.*;
  6. import java.io.*;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. Box boxContainer = new BoxContainer(
  14. new Leaf("red","fresh"),
  15. new Leaf("white","dry"),
  16. new Leaf("black","dry"),
  17. new Leaf("green", "fresh"),
  18. new BoxContainer(
  19. new Leaf("red","fresh"),
  20. new Leaf("white","dry"),
  21. new Leaf("black","dry"),
  22. new Leaf("green", "fresh")));
  23.  
  24. List<Leaf> leaves = boxContainer.leaves().collect(Collectors.toList());
  25. System.out.println(leaves);
  26. }
  27.  
  28. interface Box {
  29. Stream<Leaf> leaves();
  30. }
  31.  
  32. static class BoxContainer implements Box {
  33. final List<Box> allBoxes;
  34.  
  35. BoxContainer(Box... boxes) {
  36. this.allBoxes = Arrays.asList(boxes);
  37. }
  38.  
  39. @Override
  40. public Stream<Leaf> leaves() {
  41. return allBoxes.stream().flatMap(Box::leaves);
  42. }
  43. }
  44.  
  45. static class Leaf implements Box {
  46. final String color;
  47. final String state;
  48.  
  49. Leaf(String color, String state) {
  50. this.color = color;
  51. this.state = state;
  52. }
  53.  
  54. @Override
  55. public Stream<Leaf> leaves() {
  56. return Stream.of(this);
  57. }
  58.  
  59. @Override
  60. public String toString() {
  61. return "{color: " + color + ", state: " + state + "}";
  62. }
  63. }
  64. }
Success #stdin #stdout 0.18s 55444KB
stdin
Standard input is empty
stdout
[{color: red, state: fresh}, {color: white, state: dry}, {color: black, state: dry}, {color: green, state: fresh}, {color: red, state: fresh}, {color: white, state: dry}, {color: black, state: dry}, {color: green, state: fresh}]