Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.List;
  4.  
  5. public class ArrayHolder {
  6. public static void main(final String... args) {
  7.  
  8. // An array of objects that have an array as a field...
  9. final ArrayHolder[] holders = {new ArrayHolder(), new ArrayHolder(), new ArrayHolder(), new ArrayHolder()};
  10.  
  11. // Go through each element in each array the pre-Java 8 way:
  12. for (ArrayHolder holder : holders) {
  13. for (Object object : holder.getArray()) {
  14. // do the thing
  15. }
  16. }
  17.  
  18. // Do it with Java 8 Streams:
  19. Arrays.stream(holders)
  20. .map(ArrayHolder::getArray)
  21. .flatMap(Arrays::stream)
  22. .forEach(System.out::println);
  23.  
  24. // Works with lists, too.
  25. final List<ArrayHolder> holderList = Arrays.asList(holders);
  26.  
  27. holderList.stream()
  28. .map(ArrayHolder::getArray)
  29. .flatMap(Arrays::stream)
  30. .forEach(System.out::println);
  31.  
  32. // If your class has lists instead of arrays,
  33. // call the List.stream() method in the flatMap
  34. // method instead:
  35. holderList.stream()
  36. .map(ArrayHolder::getList)
  37. .flatMap(List::stream)
  38. .forEach(System.out::println);
  39.  
  40. // flatMap has compilation errors
  41. // The method flatMap(Function<? super ArrayHolder,? extends Stream<? extends R>>)
  42. // in the type Stream<ArrayHolder> is not applicable for the arguments (ArrayHolder::getArray)
  43. //
  44. // The type of getArray() from the type ArrayHolder is Object[],
  45. // this is incompatible with the descriptor's return type: Stream<? extends R>
  46. holderList.stream()
  47. .flatMap(ArrayHolder::getArray);
  48.  
  49. // flatMap has compilation errors
  50. // The method flatMap(Function<? super ArrayHolder,? extends Stream<? extends R>>)
  51. // in the type Stream<ArrayHolder> is not applicable for the arguments (ArrayHolder::getList)
  52. //
  53. // The type of getList() from the type ArrayHolder is List<Object>,
  54. // this is incompatible with the descriptor's return type: Stream<? extends R>
  55. holderList.stream()
  56. .flatMap(ArrayHolder::getList);
  57.  
  58. // Works with 2D arrays as well:
  59. final Object[][] objects = new Object[2][2];
  60.  
  61. Arrays.stream(objects)
  62. .flatMap(Arrays::stream);
  63. }
  64.  
  65. public Object[] getArray() {
  66. return new Object[5];
  67. }
  68.  
  69. public List<Object> getList() {
  70. return new ArrayList<>();
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement