Advertisement
ivana_andreevska

AV5 Word Count(Map)

Aug 10th, 2022
1,072
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.59 KB | None | 0 0
  1. package AV5;
  2.  
  3. import javax.sound.sampled.Line;
  4.  
  5. public class LineCounter {
  6.     private int lines;
  7.     private int words;
  8.     private int chars;
  9.  
  10.     public LineCounter(int lines, int words, int chars) {
  11.         this.lines = lines;
  12.         this.words = words;
  13.         this.chars = chars;
  14.     }
  15.  
  16.     public LineCounter(String line) {
  17.         ++lines;
  18.         words = line.split("\\s+").length;
  19.         chars = line.length();
  20.     }
  21.  
  22.     public LineCounter sum(LineCounter other) {
  23.         return new LineCounter(this.lines + other.lines,
  24.                 this.words + other.words,
  25.                 this.chars + other.chars);
  26.     }
  27.  
  28.     @Override
  29.     public String toString() {
  30.         return String.format("Lines : %d , Words: %d , Chars: %d", lines, words, chars);
  31.     }
  32. }
  33.  
  34.     public static void readDataWithBufferedReaderAndMapReduce(InputStream inputStream)
  35.     {
  36.         BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
  37.         LineCounter result = bufferedReader.lines()
  38.                 //mapiraj od linija vo objekt
  39.                 //za sekoja linija ke se napravi nov line counter
  40.                 .map(l -> new LineCounter(l))
  41.                 //reduce prima 2 raboti->od 10 line counteri napravi 1->od poveke nesta sklopi gi vo edno nesto
  42.                 .reduce(
  43.                         new LineCounter(0, 0, 0),
  44.                         //left e momentot do rezultatot a right posle toa
  45.                         (left, right) -> left.sum(right)
  46.                 );
  47.         //reduce e terminalna akcija
  48.         System.out.println(result);
  49.     }
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement