iamaamir

Operations on Arrays with Stream

Nov 15th, 2015
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.78 KB | None | 0 0
  1. int[] a = {2,5,4,6,9,7,4,5,8,7,4,5,6,3};
  2.         int[] b = {6,9,8,7,4,2,3,6,5,2,1,4,7,8,5,6,3,6};
  3.        
  4.         //combine arrays
  5.         IntStream combined = Stream.of(a,b).flatMapToInt(IntStream::of);
  6.        
  7.         //remove duplicates
  8.         IntStream distinct = combined.distinct();
  9.        
  10.         //sort
  11.         IntStream sorted = distinct.sorted();
  12.        
  13.         //filter some value
  14.         IntStream lessThenFive = sorted.filter(n -> n<=5);
  15.        
  16.         //print array
  17.         lessThenFive.forEach(System.out::println);
  18.        
  19.        
  20.         //sum of all
  21. //        int sum = sorted.sum();
  22.        
  23.         /*
  24.         Note: sum and forEach are termianl methods so the stream will be close
  25.         */
  26.        
  27.        
  28.        
  29.         //more to come
Add Comment
Please, Sign In to add comment