Showing posts with label Stream. Show all posts
Showing posts with label Stream. Show all posts

Friday, January 1, 2016

Java 8 - Streams (Part - II)

In the previous post, We learnt - What are Streams, How to create, How to Use and What are the operations that can be performed against them. Now we will continue on operations to get insights about the Streams.

Terminal and Intermediate Operations

Operations on Streams are two types. One is Intermediate Operation which returns a stream on which we can perform another operation. Second is Terminal Operation which returns a result other than stream. In the last post, we saw forEach operation which is a terminal operation, whereas sort operation which is a intermediate operation because it returns an another stream. Now, we will see some other important operations (both terminal and intermediate operations).

Count

Count operation is a Terminal operation which returns the number of the elements in the current Stream.
List<String> list = Arrays.asList("a1","a2","b","b","c1","c2");
System.out.println(list.stream().collect()); // This prints the value of 6

Reduce

Reduce operation (Terminal operation) reduces the elements in a stream using an operation. See this
List<String> list = Arrays.asList("a1","a2","b","b","c1","c2");
 list.stream().reduce((s1,s2) -> s1 + "-"+ s2 ).ifPresent(System.out::println); //prints a1-a2-b-b-c1-c2

Filter

Filter operation (Intermediate Operation) filters some of the elements in the stream based on the operation passed to it.
List<String> list = Arrays.asList("a1","a2","b","b","c1","c2");
list.stream().filter(a -> a.startsWith("a")).forEach(System.out::println); //prints a1 and a2

Match

Match Operation (Terminal Operation) returns boolean value based on the operation associated with it. We can do three match operations : anyMatch, allMatch and noneMatch. Each of these returns a value (true or false) based on the match criteria.
List<String> list = Arrays.asList("a1","a2","b","b","c1","c2");
System.out.println(list.stream().allMatch((a) -> a.startsWith("a")));  // false
System.out.println(list.stream().anyMatch((a) -> a.startsWith("a")));  // true
System.out.println(list.stream().noneMatch((a) -> a.startsWith("d"))); // true

Map

Map Operation (Intermediate Operation) converts each of the element in stream into another object via the operation passed to it. When this map operation combined with other operations like filter, reduce, forEach etc.. gives trivial results.
See below an example of how to make all the elements in the stream which start with "b" to upper case.
List<String> list = Arrays.asList("apple","biscuit","blah","cupcake","cat");
list.stream().filter(a -> a.startsWith("b")).map(String::toUpperCase).forEach(System.out::println);

Collect

Collect is one of the most important feature/method of the Stream class. Collect is used to convert the Stream into a List, Set or Map. Collect method accepts a Collector which can perform operations like Supplier, Combiner, Accumulator or Finisher. Let's look at some of them.
List<String> list = Arrays.asList("a1","a2","b","b","c1","c2");
Set<String> set = list.stream().collect(Collectors.toSet());
set.stream().forEach(System.out::println);
Above, we are trying to convert a given stream into a Set (As we know the property of Set - it doesn't hold duplicate values. So b will be dropped when it prints the values on the console.
Look at, another example how to group the stream using collect method
List<String> list = Arrays.asList("a1","a2","b","b","c1","c2");
Map<Integer,List<String>> map = list.stream().collect(Collectors.groupingBy((String p) -> p.length()));
System.out.println(map);
The above code prints the data to console as
{1=[b, b], 2=[a1, a2, c1, c2]}
This also helps to summarize the operations like min, max, average, count etc. Let's see how to do that
List<String> list = Arrays.asList("a1","a2","b","b","c1","c2");
IntSummaryStatistics stats = list.stream().collect(Collectors.summarizingInt((String t) -> t.length()));
System.out.println(stats); // This will print IntSummaryStatistics{count=6, sum=10, min=1, average=1.666667, max=2}
So far we have seen some built-in Collectors, now we will see how to create a collector with all of it's features (Supplier, Combiner, Accumulator and Finisher)
List<String> list = Arrays.asList("a1","a2","b","b","c1","c2"); 
Collector<String, StringJoiner, String> sCollector = 
      Collector.of(() -> new StringJoiner(" | "),        // supplier
      (j, p) -> j.add(p),                               // accumulator
      (j1, j2) -> j1.merge(j2),                         // combiner
      StringJoiner::toString);                          // finisher
        
String str = list.stream().collect(sCollector);
System.out.println(str); // Prints a1 | a2 | b | b | c1 | c2
The output simply explains what is being done using the streams (merging the strings using StringJoiner with pipe as a delimiter). This works more better if we are using it on objects with some calculations on it instead of strings.

Parallel Streams

Parallel Operations in Java made easier after the introduction of Fork/Join framework. To do that, we need to implement the same in our programming. In Streams it's very easy, just use .parallelStream to get the parallel stream instead of .stream in each of the examples above and make parallel operations. So, depending on the type of operation and requirement either we can call a sequential stream (using stream() method) or parallel stream (using parallelStream() method). Try replacing all the above examples with parallelStream and see the results.

Happy Learning!!!

Saturday, November 28, 2015

Java 8 - Streams (Part - I)

Stream represents a sequence of elements which can calculate or compute on-demand. Stream is an interface like an Iterator but it can do parallel processing. In other words, we can say Stream is a lazy collection where the values are computed on-demand.

How to Create

Streams are defined in java.util.stream package. Stream can be obtained using various options but a simple way is to get Stream is from Collection Interface. A default method defined as stream in Collection Interface to get it from the respective collection built. This is one of the best example to explain why the default methods are introduced in Java 8. See my previous post for more details on default methods. Collection Interface has two default methods for streams
  • stream(): Returns a stream associated with the collection for processing
  • parallelStream(): Same as stream method but returns for parallel processing. 
Stream here is the generic type. There are few streams defined for the primitive types as IntStream, DoubleStream, LongStream etc.

How to Use

As mentioned earlier - Streams are like Iterators or more than Iterators. Streams can be used to find an element, get first element, sort the elements etc. Apart from using streams on Collections, they can be used to operate on Paths, files, range of numbers etc. We will see few of them with examples

Streaming Files

BufferedReader class has got a new method lines() to return the lines in that file as Stream. See below
        try (FileReader fr = new FileReader("/tmp/sample.txt");
                BufferedReader br = new BufferedReader(fr))
        {
            br.lines().forEach(System.out::println);
        }
The above code returns the Stream which represents the sequence of lines in the file /tmp/sample.txt and, prints them. To add to it, Stream has got a method forEach to iterate over it. The Files class has also has a method lines() to read the Path as stream.
        try (Stream<String> st = Files.lines(Paths.get("/tmp/sample.txt")))
        {
            st.forEach(System.out::println);
        }

Streaming Patterns

Pattern can also return a Stream object with the matched values. Lets see that
        Pattern p = Pattern.compile("-");
        p.splitAsStream("5-13-93").forEach(System.out::println);
This will split the pattern 5-13-93 into three integers (5,13 and 93) and prints them.

Streaming Range

Stream interface has method to find range of primitive types (Int, Double or Long) as a Stream itself. We can use the respective Stream Interface (IntStream, DoubleStream and LongStream) to get the range associated with it. See - for example
IntStream.range(10, 20).forEach(System.out::println);

Stream Functions

Stream provides various methods to operate on Collections. We will discuss few of them here with examples. Most of the methods of Stream interface take lambda expression as argument (i.e. a method name - See Lambda Expressions for more details).

of:

This is a static method defined in Stream Interface to create a generic Stream. The method exists in other specific Streams like Double, Long etc to create its own type.
Stream<String> stream = Stream.of("Veeresh", "Blog", "Stream")

forEach:

The function will iterate through the Stream. All the above example has got forEach with prints to console

sort:

This method sorts the Stream elements associated with it in natural order (i.e. ascending order). See here
Stream.of("Veeresh", "Blog", "Stream").sorted().forEach(System.out::println);
The above code prints the sorted names. sort() is a very lazy function, means it doesn't effect until you call any other method after/before sort. In the above example - When the sort method was executed nothing changed on the Stream. Once the foreach method was called - the sorting was done.

Apart from these - stream has few other methods which are more powerful and useful which reduces developer effort, Increases readability and reduces LOC. We will discuss those in the next post. For now - this is it.

Happy Learning!!!!