Streams in java are somewhat like iterators, in that they provide an-element-at-a-time interface.
However, they can also be processed in parallel.
And operations like filter, map, reduce, collect can be applied.
Below is a example of how the code can be really succinct.
We read a text file, and group by the first column, producing counts per group in a few lines:
Map mresult = Files.readAllLines( Paths.get("/home/test/testaccess.log")).stream()
.map( line-> line.substring(0, line.indexOf(" ") ) )
.collect( Collectors.groupingBy( line->line, Collectors.counting()) );
System.out.println( mresult);
However, they can also be processed in parallel.
And operations like filter, map, reduce, collect can be applied.
Below is a example of how the code can be really succinct.
We read a text file, and group by the first column, producing counts per group in a few lines:
Map mresult = Files.readAllLines( Paths.get("/home/test/testaccess.log")).stream()
.map( line-> line.substring(0, line.indexOf(" ") ) )
.collect( Collectors.groupingBy( line->line, Collectors.counting()) );
System.out.println( mresult);
No comments:
Post a Comment