Friday, November 19, 2021

Java Tutorial: BaseStream Interface

Chapters

BaseStream Interface

Base interface for streams, which are sequences of elements supporting sequential and parallel aggregate operations. BaseStream is the superinterface of DoubleStream, IntStream, LongStream and Stream<T>. I'll demonstrate some methods of this interface. More information can be found in the documentation.

isParallel() Method

Method Form: boolean isParallel()
Returns whether this stream, if a terminal operation were to be executed, would execute in parallel. Calling this method after invoking a terminal stream operation method may yield unpredictable results.
import java.util.stream.Stream;
import java.util.Arrays;
import java.util.List;
  
public class SampleClass{
  
  public static void main(String[] args){
    List<String> list =
    Arrays.asList("Apple","Carrot",
                  "Mango","Melon");
    
    Stream<String> stream =
    list.parallelStream();
    
    if(stream.isParallel()){
      StringBuilder sb = 
      stream.collect(StringBuilder::new,
             (i,j) -> i.append("-"+j+"-"),
             (x,y) -> x.append("|").append(y));
      System.out.println(sb.toString());
    }
  }
}

Result
-Apple-|-Carrot-|-Mango-|-Melon-
onClose() Method

Method form: S onClose(Runnable closeHandler)
Returns an equivalent stream with an additional close handler. Close handlers are run when the close() method is called on the stream, and are executed in the order they were added. All close handlers are run, even if earlier close handlers throw exceptions.

If any close handler throws an exception, the first exception thrown will be relayed to the caller of close(), with any remaining exceptions added to that exception as suppressed exceptions (unless one of the remaining exceptions is the same exception as the first exception, since an exception cannot suppress itself.) May return itself. This is an intermediate operation.
import java.util.stream.Stream;
import java.util.ArrayList;

public class SampleClass{
  
  public static void main(String[] args){
  
    ArrayList<String> ar =
    new ArrayList<>();
    
    ar.add("Apple");
    ar.add("Melon");
    ar.add("Mango");
    ar.add("Avocado");
    ar.add("Watermelon");
    ar.add("Mangosteen");
    
    try(Stream<String> stream =
        ar.stream()){
      Object[] subFruits =
      stream.onClose(() -> 
       System.out.println("Print this message"
                 +" before closing."))
      .filter(f -> f.startsWith("M"))
      .sorted().toArray();
    
    System.out.println("Fruits that start "
                       +"with \"M\"");
    for(Object obj : subFruits)
      System.out.println(obj);
    }
    System.out.println("Stream is closed.");
    
  }
}

Result
Fruits that start with "M"
Mango
Mangosteen
Melon
Print this before closing.
Stream is closed.
Take note, most streams are not necessary to be closed. However, streams that uses IO resources are required to be closed. In the example above, the stream there is not necessary to be closed because that stream is not using IO resources. The example above is just a mere demonstration of onClose() method.

According to the Stream documentation:
Streams have a BaseStream.close() method and implement AutoCloseable. Operating on a stream after it has been closed will throw IllegalStateException. Most stream instances do not actually need to be closed after use, as they are backed by collections, arrays, or generating functions, which require no special resource management.

Generally, only streams whose source is an IO channel, such as those returned by Files.lines(Path), will require closing. If a stream does require closing, it must be opened as a resource within a try-with-resources statement or similar control structure to ensure that it is closed promptly after its operations have completed.

parallel() Method

Returns an equivalent stream that is parallel. May return itself, either because the stream was already parallel, or because the underlying stream state was modified to be parallel. This is an intermediate operation.
import java.util.stream.Stream;
import java.util.Arrays;

public class SampleClass{
  
  public static void main(String[] args){
  
     String[] ar = {"Apple","Melon","Mango"};
    
     Stream<String> stream =
     Arrays.stream(ar).parallel();
    
     if(stream.isParallel()){
       StringBuilder sb = 
       stream.collect(StringBuilder::new,
             (i,j) -> i.append("-"+j+"-"),
             (x,y) -> x.append("|").append(y));
      System.out.println(sb.toString());
    }
  }
}

Result
-Apple-|-Melon-|-Mango-
sequential() Method

Returns an equivalent stream that is sequential. May return itself, either because the stream was already sequential, or because the underlying stream state was modified to be sequential. intermediate operation.
import java.util.stream.Stream;
import java.util.Arrays;
import java.util.List;
  
public class SampleClass{
  
  public static void main(String[] args){
    List<String> list =
    Arrays.asList("Apple","Carrot",
                  "Mango","Melon");
    
    Stream<String> stream =
    list.parallelStream().sequential();
    
    if(!stream.isParallel())
      System.out.println("stream is sequential.");
      
    System.out.println("Count: " + stream.count());
  }
}

Result
stream is sequential.
Count: 4
unordered() Method

Returns an equivalent stream that is unordered. May return itself, either because the stream was already unordered, or because the underlying stream state was modified to be unordered. This is an intermediate operation.
import java.util.stream.Stream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
  
public class SampleClass{
  
  public static void main(String[] args){
    List<String> list =
    Arrays.asList("Apple");
    
    Stream<String> s1 =
    list.stream();
    
    Stream<String> s2 =
    s1.unordered();
      
    if(s1 != s2)
      System.out.println("unordered() doesn't "
      +"return s1. list is now unordered.");
      
    HashSet<String> hs =
    new HashSet<>();
    
    s1 = hs.stream();
    s2 = s1.unordered();
    
    if(s1 == s2)
      System.out.println("unordered() "
      +"returns s1. hs is already unordered.");
  }
}

Result
unordered() doesn't return s1. list is now unordered.
unordered() returns s1. hs is already unordered.

No comments:

Post a Comment