Tuesday, December 30, 2014

JDK 8: Stream API



Stream API

  • The Stream interface is located in the java.util.stream package.
  • It represents a sequence of objects somewhat like the Iterator interface. However, unlike the Iterator, it supports parallel execution.
  • The Stream interface supports the map/filter/reduce pattern and executes lazily, forming the basis (along with lambdas) for functional-style programming in Java 8.
  • There are also corresponding primitive streams (IntStream, DoubleStream, and LongStream) for performance reasons.

How to create Stream which are multi core friendly




try (FileReader fr = new FileReader("text.txt");
BufferedReader br = new BufferedReader(fr)) {




// Read the line and Print


br.lines().forEach(System.out::println);



// Read the line and sort


br.lines().sorted(( x1, x2) -> x1.compareTo(x2))

.forEach(System.out::println);


// Read the line and sort and filter and finally print


br.lines().sorted((String x1, String x2) -> x1.compareTo(x2))

.filter(line -> line.contains("x"))

.forEach(System.out::println);

} catch (Exception e) {

// TODO: handle exception


e.printStackTrace();




}




Stream API operations

  • There are several static methods on the  java.nio.file.Files class for navigating file trees using a Stream.
  • list(Path dir) – Stream of files in the given directory.
  • walk(Path dir)– Stream that traverses the file tree depth-first starting at the given directory.
  • walk(Path dir, int maxDepth) – Same as walk(dir) but with a maximum depth.
  • Streaming text pattern
Pattern patt = Pattern.compile(",");

patt.splitAsStream("a,b,c").forEach(System.out::println);



Reactions:

0 comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More