Sunday, November 21, 2021

Java Tutorial: Iterators

Chapters

Iterators

Java has different type of iterators. The very first iterator is the Enumeration. New iterators, like the Iterator Interface, differ from enumerations in two ways:
  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.
An Enumeration can be converted into an Iterator by using the Enumeration.asIterator() method. Iterators are often used for the Collections Framework.

Enumeration

An object that implements the Enumeration interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series. This iterator is mainly used for Vector, Stack and HashTable which are legacy collections.

This example demonstrates Enumeration.
import java.util.Enumeration;
import java.util.Vector;

public class SampleClass{

  public static void main(String[] args){
  
    Vector<String> vc =
    new Vector<>();
    
    vc.add("Apple");
    vc.add("Orange");
    vc.add("Melon");
    
    Enumeration<String> en =
    vc.elements();
    
    while(en.hasMoreElements())
      System.out.println(en.nextElement());
  }
}

Result
Apple
Orange
Mango
In the example above, we create a Vector object and add three strings to it. Then, we create an Enumeration for Vector by calling the elements() method. Then, we traverse Vector via Enumeration starting from the first index. hasMoreElements() returns true if the Enumeration's pointer is not past beyond the last index. nextElement() returns the next available element where the Enumeration's pointer is pointing.

Pointer is just like a cursor that is pointing at some index. In Enumeration, pointer starts at index 0. Then, after nextElement() is invoked, the pointer will move to the next index until it reaches the last index.

Ways of Getting Iterator

There are several methods that return an instance that is related to Iterator interface. Each method returns a particular iterator.

iterator() Method

This method returns an Iterator with a pointer that starts at first index and end at last index. This method is available to almost every collection that is a subclass of Collection interface.
import java.util.Iterator;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<String> ar =
    new ArrayList<>();
    
    ar.add("Apple");
    ar.add("Orange");
    ar.add("Melon");
    
    Iterator<String> it =
    ar.iterator();
    
    while(it.hasNext())
      System.out.println(it.next());
  }
}

Result
Apple
Orange
Melon
hasNext() returns true if the ArrayList's point is not past beyond last index. next() returns the next available element where the pointer is pointing. We can use Iterator to remove elements by using the remove() method. We can also assign a lambda expression to our iterator by using the forEachRemaining() method.

descendingIterator() Method

This method is available from the Deque interface. LinkedList and ArrayDeque inherit this method. The Iterator that is returned by this method has a pointer that starts at last(tail) index and end at first(head) index.
import java.util.Iterator;
import java.util.LinkedList;

public class SampleClass{

  public static void main(String[] args){
  
    LinkedList<String> ar =
    new LinkedList<>();
    
    ar.add("Apple");
    ar.add("Orange");
    ar.add("Melon");
    
    Iterator<String> it =
    ar.descendingIterator();
    
    while(it.hasNext())
      System.out.println(it.next());
  }
}

Result
Melon
Orange
Apple
listIterator() Method

This method returns a ListIterator. ListIterator is an iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list.

A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). listIterator() is available from List and available to its subclasses. This iterator can get, remove and set an element from an index.
import java.util.ArrayList;
import java.util.ListIterator;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<String> ar =
    new ArrayList<>();
    
    ar.add("Apple");
    ar.add("Orange");
    ar.add("Melon");
    ar.add("Melon");
    
    ListIterator<String> li =
    ar.listIterator();
    
    String next = "";
    String prev = "";
    
    int nextIndex = 0;
    int prevIndex = 0;
    System.out.println("Checking for nearest"
    +" duplicate...");
    while(li.hasNext()){
      nextIndex = li.nextIndex();
      next = li.next();
        
      if(next == prev){
        System.out.println(prev + " at index "
        +prevIndex+" is equal to " + next +
        " at index "+nextIndex);
        
        System.out.println("Setting "+prev+
        " at index " + prevIndex + " to "
        +"Watermelon...");
        
        if(li.hasPrevious()){
          prevIndex = li.previousIndex();
          
          while(prevIndex != 1){
            prev = li.previous();
            prevIndex = li.previousIndex();
          }
          
          li.set("Watermelon");
          continue;
        }
      }
      
      prev = next;
      prevIndex = nextIndex;
    }
    
    //We need to create another
    //listIterator to iterate
    //to the ArrayList again
    li = ar.listIterator();
    
    System.out.println("Elements...");
    while(li.hasNext())
      System.out.println(li.next());
    
  }
}

Result
Checking for nearest duplicate...
Melon at index 2 is equal to Melon at index 3
Setting Melon at index 2 to Watermelon...
Elements...
Apple
Orange
Watermelon
Melon
ListIterator's pointer doesn't directly point at elements. it points in-between elements. For example, next() returns "Orange" which is located at index 1. Now, the pointer points at the middle of index 1 and index 2.Now, If we call previousIndex(), it will return index 1. If we call nextIndex(), it will return index 2.

spliterator() Method

This method returns a Spliterator that performs traversing and partitioning elements of a source. The source of elements covered by a Spliterator could be, for example, an array, a Collection, an IO channel, or a generator function. A Spliterator may also partition off some of its elements (using trySplit()) as another Spliterator, to be used in possibly-parallel operations.

Operations using a Spliterator that cannot split, or does so in a highly imbalanced or inefficient manner, are unlikely to benefit from parallelism. Traversal and splitting exhaust elements; each Spliterator is useful for only a single bulk computation. Let's discuss Spliterator's methods. My explanation about methods here is simplifed. Refer to the documentation for more information.

Spliterator have different types of characteristics based on a collection or a stream. It's important to know the characteristics of a particular Spliterator because some characteristics may interfere with out operation or is needed in an operation. For example, if a Spliterator has CONCURRENT characteristic then multiple threads may safely concurrently modify this iterator. Spliterator is available from Collection and BaseStream.

characteristics() Method

Returns a set of characteristics of this Spliterator and its elements. The result is represented as ORed(Bit field) values from ORDERED, DISTINCT, SORTED, SIZED, NONNULL, IMMUTABLE, CONCURRENT, SUBSIZED. Repeated calls to characteristics() on a given spliterator, prior to or in-between calls to trySplit, should always return the same result.

If a Spliterator reports an inconsistent set of characteristics (either those returned from a single invocation or across multiple invocations), no guarantees can be made about any computation using this Spliterator.
import java.util.ArrayList;
import java.util.Spliterator;

public class SampleClass{

  public static void main(String[] args){
    
    ArrayList<String> ar =
    new ArrayList<>();
    
    ar.add("Apple");
    ar.add("Orange");
    ar.add("Melon");
    
    Spliterator<String> st =
    ar.spliterator();
    
    int arChars = Spliterator.ORDERED |
                  Spliterator.SIZED |
                  Spliterator.SUBSIZED;
                  
    if(arChars == st.characteristics())
      System.out.println("Spliterator of "
      +"ArrayList is\nSIZED, SUBSIZED and ORDERED.");
  }
}

Result
Spliterator of ArrayList is
SIZED, SUBSIZED and ORDERED.
hasCharacteristics() Method

Method form:default boolean hasCharacteristics(int characteristics)
Returns true if this Spliterator's characteristics() contain all of the given characteristics.
import java.util.HashSet;
import java.util.Spliterator;

public class SampleClass{

  public static void main(String[] args){
  
    HashSet<String> hs =
    new HashSet<>();
    
    hs.add("Apple");
    hs.add("Orange");
    hs.add("Melon");
    
    Spliterator<String> st =
    hs.spliterator();
    
    if(st.hasCharacteristics(Spliterator.ORDERED))
      System.out.println("st is ORDERED.");
      
    if(st.hasCharacteristics(Spliterator.DISTINCT))
      System.out.println("st is DISTINCT.");
      
    if(st.hasCharacteristics(Spliterator.SORTED))
      System.out.println("st is SORTED.");
      
    if(st.hasCharacteristics(Spliterator.SIZED))
      System.out.println("st is SIZED.");
      
    if(st.hasCharacteristics(Spliterator.NONNULL))
      System.out.println("st is NONNULL.");
      
    if(st.hasCharacteristics(Spliterator.IMMUTABLE))
      System.out.println("st is IMMUTABLE.");
      
    if(st.hasCharacteristics(Spliterator.CONCURRENT))
      System.out.println("st is CONCURRENT.");
      
    if(st.hasCharacteristics(Spliterator.SUBSIZED))
      System.out.println("st is SUBSIZED.");
  }
}

Result
st is DISTINCT.
st is SIZED.
We can put multiple characteristics as a single argument in hasCharacteristics().
import java.util.ArrayList;
import java.util.Spliterator;

public class SampleClass{

  public static void main(String[] args){
    
    ArrayList<String> ar =
    new ArrayList<>();
    
    ar.add("Apple");
    ar.add("Orange");
    ar.add("Melon");
    
    Spliterator<String> st =
    ar.spliterator();
    
    int arChars = Spliterator.ORDERED |
                  Spliterator.SIZED |
                  Spliterator.SUBSIZED;
                  
    if(st.hasCharacteristics(arChars))
      System.out.println("Spliterator of "
      +"ArrayList is\nSIZED, SUBSIZED and ORDERED.");
  }
}

Result
Spliterator of ArrayList is
SIZED, SUBSIZED and ORDERED.
tryAdvance() Method

Method form: boolean tryAdvance(Consumer<? super T> action)
If a remaining element exists, performs the given action on it, returning true; else returns false. If this Spliterator is ORDERED the action is performed on the next element in encounter order. Exceptions thrown by the action are relayed to the caller.

Subsequent behavior of a spliterator is unspecified if the action throws an exception.
import java.util.Spliterator;
import java.util.ArrayList;
import java.util.function.Consumer;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<String> ar =
    new ArrayList<>();
    
    ar.add("Apple");
    ar.add("Orange");
    ar.add("Melon");
    
    Spliterator<String> st =
    ar.spliterator();
    
    Consumer<String> cons =
    (e) -> System.out.println("-"+e+"-");
    
    while(st.tryAdvance(cons));
  }
}

Result
-Apple-
-Orange-
-Melon-
trySplit() Method

If this spliterator can be partitioned, returns a Spliterator covering elements, that will, upon return from this method, not be covered by this Spliterator that called this method. If this Spliterator is ORDERED, the returned Spliterator must cover a strict prefix of the elements.

Unless this Spliterator covers an infinite number of elements, repeated calls to trySplit() must eventually return null. Upon non-null return:
  • the value reported for estimateSize() before splitting, must, after splitting, be greater than or equal to estimateSize() for this and the returned Spliterator; and
  • if this Spliterator is SUBSIZED, then estimateSize() for this spliterator before splitting must be equal to the sum of estimateSize() for this and the returned Spliterator after splitting.
This method may return null for any reason, including emptiness, inability to split after traversal has commenced, data structure constraints, and efficiency considerations.
import java.util.Spliterator;
import java.util.ArrayList;
import java.util.Collections;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<Integer> ar =
    new ArrayList<>();
    
    Collections.addAll(ar,1,2,3,4,5,6,7,8
    ,9,10,11,12,13,14,15);
    
    Spliterator<Integer> st1 =
    ar.spliterator();
    
    Spliterator<Integer> st2 =
    st1.trySplit();
    
    Spliterator<Integer> st3 =
    st2.trySplit();
    
    st1.forEachRemaining(
	(e) -> System.out.println(e));
    
    System.out.println("----------");
    
    st2.forEachRemaining(
	(e) -> System.out.println(e));
    
    System.out.println("----------");
    
    st3.forEachRemaining(
	(e) -> System.out.println(e));
  }
}

Result
8
9
10
11
12
13
14
15
----------
4
5
6
7
----------
1
2
3
In the example above, we use Spliterator in sequential manner. We also use forEachRemaining() for traversing spliterators. If you want to run spliterators in parallel, Use Fork/Join framework or multithreading in conjunction with Spliterator.

estimateSize() Method

Returns an estimate of the number of elements that would be encountered by a forEachRemaining() traversal, or returns Long.MAX_VALUE if infinite, unknown, or too expensive to compute.

If this Spliterator is SIZED and has not yet been partially traversed or split, or this Spliterator is SUBSIZED and has not yet been partially traversed, this estimate must be an accurate count of elements that would be encountered by a complete traversal. Otherwise, this estimate may be arbitrarily inaccurate, but must decrease as specified across invocations of trySplit().
import java.util.Spliterator;
import java.util.HashSet;
import java.util.Collections;

public class SampleClass{

  public static void main(String[] args){
  
    HashSet<Integer> ar =
    new HashSet<>();
    
    Collections.addAll(ar,1,2,3,4,5,6,7,8
    ,9,10,11,12,13,14,15);
    
    Spliterator<Integer> st1 =
    ar.spliterator();
    
    if(!st1.hasCharacteristics
       (Spliterator.SUBSIZED))
       System.out.println("This spliterator is "
       +"not SUBSIZED.\nEstimate size may be"+
       " inacurrate after split.");
      
    
    System.out.println("st1 size before "+
    "split: " + st1.estimateSize());
    
    Spliterator<Integer> st2 =
    st1.trySplit();
    
    System.out.println("st1 size after "+
    "split: " + st1.estimateSize());
    
    st1.forEachRemaining(
	(e) -> System.out.println("st1: " + e + " "));
    
    st2.forEachRemaining(
	(e) -> System.out.println("st2: " + e + " "));
  }
}

Result(Result may vary)
This spliterator is not SUBSIZED.
Estimate size may be inaccurate after split.
st1 size before split: 15
st1 size after split: 7
st2: 1
st2: 2
st2: 3
st2: 4
st2: 5
st2: 6
st2: 7
st2: 8
st2: 9
st2: 10
st2: 11
st2: 12
st2: 13
st2: 14
st2: 15
In the example above, trySplit() didn't split st1 because the spliterator is not ORDERED. It means that st1 size after split was innacurate. st1 size after split was innacurate because the spliterator is not SUBSIZED. Take a look at this next example.
import java.util.Spliterator;
import java.util.ArrayList;
import java.util.Collections;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<Integer> ar =
    new ArrayList<>();
    
    Collections.addAll(ar,1,2,3,4,5,6,7,8
    ,9,10,11,12,13,14,15);
    
    Spliterator<Integer> st1 =
    ar.spliterator();
    
    if(st1.hasCharacteristics
       (Spliterator.SUBSIZED))
       System.out.println("This spliterator is "
       +"SUBSIZED.");
      
    
    System.out.println("st1 size before "+
    "split: " + st1.estimateSize());
    
    Spliterator<Integer> st2 =
    st1.trySplit();
    
    System.out.println("st1 size after "+
    "split: " + st1.estimateSize());
    
    st1.forEachRemaining(
	(e) -> System.out.println("st1: " + e + " "));
    
    st2.forEachRemaining(
	(e) -> System.out.println("st2: " + e + " "));
  }
}

This spliterator is SUBSIZED.
st1 size before split: 15
st1 size after split: 8
st1: 8
st1: 9
st1: 10
st1: 11
st1: 12
st1: 13
st1: 14
st1: 15
st2: 1
st2: 2
st2: 3
st2: 4
st2: 5
st2: 6
st2: 7
In this example above, the spliterator is SUBSIZED. Thus, st1 size after the split is accurate.
getExactSizeIfKnown() Method

Convenience method that returns estimateSize() if this Spliterator is SIZED, else -1.
import java.util.Spliterator;
import java.util.HashSet;
import java.util.Collections;

public class SampleClass{

  public static void main(String[] args){
  
    HashSet<Integer> ar =
    new HashSet<>();
    
    Collections.addAll(ar,1,2,3,4,5,
                          6,7,8,9,10);
    
    Spliterator<Integer> st1 =
    ar.spliterator();
    
    if(!st1.hasCharacteristics
       (Spliterator.SUBSIZED))
       System.out.println("This spliterator is "
       +"not SUBSIZED.\nSplitted spliterators off"
       +"\nof this spliterator are not SIZED and SUBSIZED.");
    
    long result = st1.getExactSizeIfKnown();
    System.out.println("st1 size: " + result);
    
    Spliterator<Integer> st2 =
    st1.trySplit();
    
    result = st2.getExactSizeIfKnown();
    
    System.out.println("st2 size: " + result);
  }
}

Result
This spliterator is not SUBSIZED.
Splitted spliterators off
of this spliterator are not SIZED and SUBSIZED.
st1 size: 10
st2 size: -1
getComparator() Method

Method form: default Comparator<? super T> getComparator()
If this Spliterator's source is SORTED by a Comparator, returns that Comparator. If the source is SORTED in natural order, returns null. Otherwise, if the source is not SORTED, throws IllegalStateException.
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.Spliterator;
import java.util.Collections;

public class SampleClass{

  public static void main(String[] args){
  
    TreeSet<Integer> ts =
    new TreeSet<>(Collections.reverseOrder());
    
    Collections.addAll(ts,1,2,3,4,5);
    
    Spliterator<Integer> st =
    ts.spliterator();
    
    ArrayList<Integer> ar =
    new ArrayList<>();
    
    Collections.addAll(ar,6,7,8,9,10);
    Collections.sort(ar, st.getComparator());
    
    System.out.println("TreeSet Elements...");
    while(st.tryAdvance((e) -> 
      System.out.print(e + " ")));
    
    System.out.println();
    
    System.out.println("ArrayList Elements...");
    for(Integer i : ar)
      System.out.print(i + " ");
  }
}

Result
Treeset Elements...
5 4 3 2 1

ArrayList Elements...
10 9 8 7 6
OfDouble, OfInt, OfLong and OfPrimitive

Spliterator.OfDouble, Spliterator.OfInt and Spliterator.OfLong are spliterators that specialize in double, int and long primitive types respectively. This spliterators improve performance for processing primitive types.

This example demonstrates Spliterator.OfInt
import java.util.Spliterator;
import java.util.Arrays;
import java.util.function.Consumer;

public class SampleClass{

  public static void main(String[] args){
  
    int[] ints = {1,2,3,4,5};
    
    Spliterator.OfInt so =
    Arrays.stream(ints).spliterator();
    
    Consumer<Integer> cons =
    (e) -> System.out.print((e*e) + " ");
    
    while(so.tryAdvance(cons));
  }
}

Result
1 4 9 16 25
In the example above, we use a Consumer functional interface. This interface wraps primitive types to their respective wrapper classes, which may undermine the performance boost of these specialized spliterators. If wrapper classes are not necessary in our program, we can drop them.

There are functional interfaces that don't wrap primitives into their respective wrapper classes. For int primitive, we can use the IntConsumer functional interface.
import java.util.Spliterator;
import java.util.Arrays;
import java.util.function.IntConsumer;

public class SampleClass{

  public static void main(String[] args){
  
    int[] ints = {1,2,3,4,5};
    
    Spliterator.OfInt so =
    Arrays.stream(ints).spliterator();
    
    IntConsumer ic =
    (e) -> System.out.print((e*e) + " ");
    
    while(so.tryAdvance(ic));
  }
}

Result
1 4 9 16 25
tryAdvance() of Spliterator.OfInt accepts Consumer and IntConsumer because in Spliterator.OfInt, tryAdvance() has this form:
tryAdvance(Consumer<? super Integer> action)

ALso, Spliterator.OfDouble, Spliterator.OfInt and Spliterator.OfLong extend OfPrimitive interface. OfPrimitive has this form of tryAdvance:
boolean tryAdvance(T_CONS action)
According to the documentation, T_CONS is the type of primitive consumer. The type must be a primitive specialization of Consumer , such as IntConsumer for Integer.

These two forms can create an ambiguity. Take a look at this example:
import java.util.Spliterator;
import java.util.Arrays;
import java.util.function.IntConsumer;

public class SampleClass{

  public static void main(String[] args){
  
    int[] ints = {1,2,3,4,5};
    
    Spliterator.OfInt so =
    Arrays.stream(ints).spliterator();
    
    while(so.tryAdvance((e) -> 
    System.out.print((e*e) + " ")));
  }
}

Result
error: reference to tryAdvance is ambiguous...

 both method tryAdvance(IntConsumer) in OfInt
 and method 
 tryAdvance(Consumer<? super Integer>)
 in OfInt match
forEachRemaining() is available to these specialized spliterators and forEachRemaining() of these specialized spliterators is also optimized for primitive types just like tryAdvance().

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.

Thursday, November 18, 2021

Java Tutorial: Stream Class

Chapters

Stream and its Pipeline

This class holds sequence of elements supporting sequential and parallel aggregate operations. To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of a source (which might be an array, a collection, a generator function, an I/O channel, etc), zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation (which produces a result or side-effect, such as count() or forEach(Consumer)).

Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed. In other words, if we want to get a result from a Stream, we need to initiate a terminal operation. The explanation in this tutorial is simplified. More information can be found in this article and this another article.

In this tutorial, we're going to use collections(ArrayList, LinkedList, etc.) and arrays as our source. Collection interface has stream() method that returns a sequential stream. stream() is a default method of Collection interface. Thus, every collections that extend Collection can access the method. You need to be knowledgable about lambda expression and generics to understand this tutorial.

This example demonstrate the usage of Stream.
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");
    
    Object[] subFruits =
    ar.stream()
      .filter(f -> f.startsWith("M"))
      .sorted().toArray();
    
    System.out.println("Fruits that start "
                       +"with \"M\"");
    for(Object obj : subFruits)
      System.out.println(obj);
  }
}

Result
Fruits that start with "M"
Mango
Mangosteen
Melon
In the example above, we call the stream() method of ArrayList that returns a sequential stream that uses ArrayList as its source. Then, we call the filter() method. This method is an intermediate operation that returns a stream with elements that is selected by the specified functionality in the method argument.

Then, we call the sorted() method. This method is a stateful intermediate operation that returns a stream that consists of sorted elements from the current stream. The sort order is according to the natural ordering of elements.

Lastly, we call toArray() method. This method is a terminal operation that returns an Object-type array that consists of elements of the current stream. In addition to Stream, which is a stream of object references, there are primitive specializations for IntStream, LongStream, and DoubleStream. These types of streams have operations that don't exist in the Stream class.

If we want a stream that runs in parallel, we use the parallelStream() method. This method returns a possibly parallel Stream with its source. It is allowable for this method to return a sequential stream. This method implements parallelism. Thus, this method benefits from multicore systems. When processing large arrays, parallel computing can improve the performance.
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");
    
    StringBuilder sb = 
    list.parallelStream()
        .collect(StringBuilder::new,
                 (i,j) -> i.append("-"+j+"-"),
                 (x,y) -> x.append("|").append(y));
    System.out.println(sb.toString());
  }
}
  
Result
-Apple-|-Carrot-|-Mango-|-Melon-
This is the form of collect() method that I used in the example above:
<R> R collect(Supplier<R> supplier,
              BiConsumer<R,? super T> accumulator,
              BiConsumer<R,R> combiner)
This method performs a mutable reduction operation on the elements of this stream. A mutable reduction is one in which the reduced value is a mutable result container(such as an ArrayList and StringBuilder) and elements are incorporated by updating the state of the result rather than by replacing the result. In Stream, Reduction simply means accumulating data and combining them as one.

Like reduce(Object, BinaryOperator), collect operations can be parallelized without requiring additional synchronization. This is a terminal operation.

The first parameter is a Supplier type. Stream initializes multiple instances of this parameter to hold the elements that we're gonna accumulate in the source. The second parameter is a BiConsumer type. This parameter accepts a lambda expression that supplies suppliers with elements of the source. The third parameter is also a BiConsumer type. This parameter concatenates results from multiple accumulators that run in parallel.

I'll demonstrate some methods of Stream class in this tutorial. More methods can be seen in the documentation.

allMatch() Method

Method form: boolean allMatch(Predicate<? super T> predicate)
Returns whether all elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated. This is a short-circuiting terminal operation.
import java.util.stream.Stream;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<Integer> ar =
    new ArrayList<>();
    
    ar.add(2);
    ar.add(4);
    ar.add(6);
    ar.add(8);
    ar.add(10);
    
    boolean result = ar.stream()
                    .allMatch(i -> (i % 2) == 0);
                    
    System.out.println("All numbers divisible by 2?");
    System.out.println(result);
  }
}

All numbers divisible by 2?
true
anyMatch() Method

Method form: boolean anyMatch(Predicate>? super T> predicate) Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated. This is a short-circuiting terminal operation.
import java.util.stream.Stream;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<Integer> ar =
    new ArrayList<>();
    
    ar.add(3);
    ar.add(4);
    ar.add(7);
    ar.add(9);
    ar.add(17);
    
    boolean result = ar.stream()
                    .anyMatch(i -> (i % 2) == 0);
                    
    System.out.println("Any number divisible by 2?");
    System.out.println(result);
  }
}

Result
Any number divisible by 2?
true
builder() Method

Returns a String.Builder object for a Stream. String.Builder is a mutable builder for a Stream. This allows the creation of a Stream by generating elements individually and adding them to the Builder (without the copying overhead that comes from using an ArrayList as a temporary buffer. We can use this builder if we want to generate elements without external source.
import java.util.stream.Stream;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<Object> ar = 
    new ArrayList<>(
    Stream.builder().add(2).add(4)
                    .add(6).add(8)
                    .build().toList());
                    
    System.out.println("Squared numbers...");
    for(int i = 0; i < ar.size(); i++){
      int num = (Integer)ar.get(i);
      System.out.print((num * num) + " ");
    }
  }
}

Result
Squared numbers...
4 16 36 64
collect() Method

This method has two forms. One of its forms has been explained in the first topic. In this topic, I'm gonna demonstrate this form.
Method form: <R, A> R collect(Collector<? super T,A,R> collector)

This method performs a mutable reduction operation on the elements of this stream using a Collector. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning.

If the stream is parallel, and the Collector is concurrent, and either the stream is unordered or the collector is unordered, then a concurrent reduction will be performed (see Collector for details on concurrent reduction.) This is a terminal operation.

When executed in parallel, multiple intermediate results may be instantiated, populated, and merged so as to maintain isolation of mutable data structures. Therefore, even when executed in parallel with non-thread-safe data structures (such as ArrayList), no additional synchronization is needed for a parallel reduction.
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
    
    ArrayList<String> ar = 
    new ArrayList<>();
    
    ar.add("The");
    ar.add("Big");
    ar.add("Brown");
    ar.add("Fox");
    
    String result =
    ar.stream().collect(Collectors.joining(" "));
               
    System.out.println(result);
  }
}

Result
The Big Brown Fox
In the example above, we call collect() method with Collectors.joining() method in the argument. Collectors interface has lots of useful static methods that return a Collector. joining(CharSeqience delimiter) method returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.
concat() Method

Method form: static <T> Stream<T> concat(Stream<? extends T> a,Stream<? extends T> b)
Creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream. The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel. When the resulting stream is closed, the close handlers for both input streams are invoked.

This method operates on the two input streams and binds each stream to its source. As a result subsequent modifications to an input stream source may not be reflected in the concatenated stream result.
import java.util.stream.Stream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<String> ar1 = 
    new ArrayList<>();
    
    Collections.addAll(ar1,"A","B","C","D");
    
    ArrayList<String> ar2 = 
    new ArrayList<>();
    
    Collections.addAll(ar2,"E","F","G","H");
    
    List<String> list =
    Stream.concat(ar1.stream(), ar2.stream())
          .toList();
    
    System.out.println("Elements...");
    for(String str : list)
      System.out.print(str + " ");
    
  }
}

Result
A B C D E F G H
count() Method

This method returns the count of elements in this stream. This is a special case of a reduction and is equivalent to:
return mapToLong(e -> 1L).sum();
This is a terminal operation.
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
    
    ArrayList<String> ar = 
    new ArrayList<>();
    
    ar.add("The");
    ar.add("Big");
    ar.add("Brown");
    ar.add("Fox");
    
    long count =
    ar.stream().count();
               
    System.out.println(count);
  }
}

Result
4
distinct() Method

Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.For ordered streams, the selection of distinct elements is stable (for duplicated elements, the element appearing first in the encounter order is preserved.) For unordered streams, no stability guarantees are made. This is a stateful intermediate operation.
import java.util.stream.Stream;
import java.util.ArrayList;
import java.util.List;

public class SampleClass{

  public static void main(String[] args){
    ArrayList<String> ar =
    new ArrayList<>();
    
    ar.add("Apple");
    ar.add("Melon");
    ar.add("Apple");
    ar.add("Avocado");
    ar.add("Watermelon");
    ar.add("Avocado");
    
    List<String> list =
    ar.stream().distinct().toList();
    
    System.out.println("Elements...");
    for(String str : list)
      System.out.print(str + " ");
  }
}

Result
Elements...
Apple Melon Avocado Watermelon
dropWhile() Method

Method form: efault Stream<T> dropWhile(Predicate<? super T> predicate) Returns, if this stream is ordered, a stream consisting of the remaining elements of this stream after dropping the longest prefix of elements that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of the remaining elements of this stream after dropping a subset of elements that match the given predicate.

If this stream is ordered then the longest prefix is a contiguous sequence of elements of this stream that match the given predicate. The first element of the sequence is the first element of this stream, and the element immediately following the last element of the sequence does not match the given predicate.

If this stream is unordered, and some (but not all) elements of this stream match the given predicate, then the behavior of this operation is nondeterministic; it is free to drop any subset of matching elements (which includes the empty set).

Independent of whether this stream is ordered or unordered if all elements of this stream match the given predicate then this operation drops all elements (the result is an empty stream), or if no elements of the stream match the given predicate then no elements are dropped (the result is the same as the input). This is a stateful intermediate operation.

Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations. Certain stream sources (such as List or arrays) are intrinsically ordered, whereas others (such as HashSet) are not. Some intermediate operations, such as sorted(), may impose an encounter order on an otherwise unordered stream, and others may render an ordered stream unordered.

import java.util.stream.Stream;
import java.util.Arrays;
import java.util.List;

public class SampleClass{

  public static void main(String[] args){
  
    String[] ar = {"Apple", "Melon", "Avocado",
                   "Watermelon","Avocado"};
    
    List<String> list =
    Arrays.stream(ar)
          .dropWhile(x -> !x.equals("Avocado"))
          .toList();
               
    System.out.println("Elements...");
    for(String str : list)
      System.out.print(str + " ");
  }
}

Result
Elements...
Avocado Watermelon Avocado
In the example above, we see that as long as the return value of predicate in dropWhile() is true, evaluated elements that is evaluated as true will be dropped. If the return value of predicate in dropWhile() is false, the evaluated element that is evaluated as false and the subsequent elements will be included in the Stream that will be returned by dropWhile().

filter() Method

Method form: Stream<T> filter(Predicate<? super T> predicate)
Returns a stream consisting of the elements of this stream that match the given predicate.
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");
    
    Object[] subFruits =
    ar.stream()
      .filter(f -> f.startsWith("M"))
      .sorted().toArray();
    
    System.out.println("Fruits that start "
                       +"with \"M\"");
    for(Object obj : subFruits)
      System.out.println(obj);
  }
}

Result
Fruits that start with "M"
Mango
Mangosteen
Melon

findAny() Method

Method form: Optional<T> findAny()
Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation.

The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)
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("Watermelon");
    ar.add("Avocado");
    
    String result = ar.stream().findAny().get();
    
    System.out.println(result);
  }
}

findFirst() Method

Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned. This is a short-circuiting terminal 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("Watermelon");
    ar.add("Avocado");
    
    String result = ar.stream().findFirst().get();
    
    System.out.println(result);
  }
}

Result
Apple

flatMap() Method

Method form: <R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.) This is an This is a intermediate operation.
import java.util.stream.Stream;
import java.util.Arrays;

public class SampleClass{

  public static void main(String[] args){
  
    Integer[][] ints = {{2,4,6},{3,7,9}};
    
    Object[] flatInts = Arrays.stream(ints)
                        .flatMap(l -> Arrays.stream(l))
                        .toArray();
                        
    System.out.println("Flattened array of "
                       +"integers.");
    
    for(Object o : flatInts)
      System.out.print(o + " ");
  }
}

Result
Flattened array of integers.
2 4 6 3 7 9
In the example above, we are able to convert two-dimensional array into a one-dimensional array. In other words, we are able to flatten a two-dimensional array.

Flattening is a process of merging several layers into one single layer. When we flatten an array(or collection), we get all elements from arrays within the array and merge all elements in a one-dimensional array.

Here's another example. This time, we're gonna modify the mapped values.
import java.util.stream.Stream;
import java.util.Arrays;

public class SampleClass{

  public static void main(String[] args){
  
    Integer[][] ints = {{2,4,6},{3,7,9}};
    
    Object[] flatInts = Arrays.stream(ints)
                        .flatMap(l -> Arrays.stream(l))
                        .map(v -> v*v)
                        .toArray();
                        
    System.out.println("Flattened array of "
                       +"integers.");
    
    for(Object o : flatInts)
      System.out.print(o + " ");
  }
}

Result
Flattened array of integers.
4 16 36 9 49 81
In the example above, we use flatMap() to map elements and put them in a flattened container. Then, we use map() to map elements in the flattened container and square them. Then, toArray() converts the flattened container into an Object-type array.

Mapping is a process of associating an element from a set to another set. Association of elements could be copying an element to another set, generating new elements from elements in the set, etc.

There are methods that are associated with flatMap(). These are: flatMapToDouble(), flatMapToInt() and flatMapToLong(). These methods don't return Stream. They return DoubleStream, IntStream and LongStream respectively. These versions of Stream are specialized in primitive wrapper classes.

This example demonstrates flatMapToInt() method.
import java.util.stream.Stream;
import java.util.stream.IntStream;
import java.util.Arrays;

public class SampleClass{

  public static void main(String[] args){
  
    Integer[][] ints = {{2,4,6},{3,7,9}};
    
    int sum = Arrays.stream(ints)
              .flatMapToInt(n -> Arrays.stream(n)
                            .mapToInt(m -> m))
              .sum();
                        
    System.out.println("sum: " + sum);
  }
}
In the example above, we get a Stream instance from ints. Then, we use flatMapToInt(). This method returns IntStream. Thus, the elements in the flattened container need to be placed in an IntStream. To achieve that, we use mapToInt() method. This method map every element in the flattened container and wrap them into IntStream. Then, we use sum() method. This method returns an int that is the sum of all elements in IntStream.

forEach() Method

Method form: void forEach(Consumer<? super T> action)
Performs an action for each element of this stream. This is a terminal operation. The behavior of this operation is explicitly nondeterministic. For parallel stream pipelines, this operation does not guarantee to respect the encounter order of the stream, as doing so would sacrifice the benefit of parallelism.

For any given element, the action may be performed at whatever time and in whatever thread the library chooses. If the action accesses shared state, it is responsible for providing the required synchronization.
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("Watermelon");
    ar.add("Avocado");
    
    ar.stream().forEach(System.out::println);
  }
}

forEachOrdered() Method

Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. This is a terminal operation. This operation processes the elements one at a time, in encounter order if one exists.

Performing the action for one element happens-before performing the action for subsequent elements, but for any given element, the action may be performed in whatever thread the library chooses. In multithreading, forEachOrdered() is more predictable than forEach(). Also, forEachOrdered() follows defined encounter order of a collection and array.
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("Watermelon");
    ar.add("Avocado");
    
    ar.stream().forEachOrdered(System.out::println);
  }
}

Result
Apple
Melon
Watermelon
Avocado

generate() Method

Method form: static <T> Stream<T> generate(Supplier<? extends T> s)
Returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc.

This example demonstrate generate() method. This example will infinitely run. You need to stop your IDE or command prompt(if you're using windows) by force to end the execution.
import java.util.stream.Stream;

public class SampleClass{

  public static void main(String[] args){
  
    Stream.generate(() -> "Hello")
          .forEach(System.out::println);
  }
}
We use the limit() to put a limit on an infinite stream like generate().
import java.util.stream.Stream;
import java.util.Random;

public class SampleClass{

  public static void main(String[] args){
  
    Object[] num = Stream.generate(() -> new Random()
                                  .nextInt(150))
                        .limit(10)
                        .toArray();
                        
    for(Object o : num)
      System.out.print(o + " ");
  }
}

iterate() Method

This method has two forms. Let's start with this form:
Method form: static <T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
This method returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying the given hasNext predicate. The stream terminates as soon as the hasNext predicate returns false.

The resulting sequence may be empty if the hasNext predicate does not hold on the seed value. Otherwise the first element will be the supplied seed value, the next element (if present) will be the result of applying the next function to the seed value, and so on iteratively until the hasNext predicate indicates that the stream should terminate.

The action of applying the hasNext predicate to an element happens-before the action of applying the next function to that element. The action of applying the next function for one element happens-before the action of applying the hasNext predicate for subsequent elements. For any given element an action may be performed in whatever thread the library chooses.
import java.util.stream.Stream;

public class SampleClass{

  public static void main(String[] args){
  
    Object[] num = Stream.iterate(0,
                   i -> i < 1000,
                   i -> (++i)*i)
                   .toArray();
                        
    for(Object o : num)
      System.out.print(o + " ");
  }
}

Result
0 1 4 25 676
Next, let's discuss the next form: static <T> Stream<T> iterate(T seed, UnaryOperator<T> f)
This method returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed, producing a Stream consisting of seed, f(seed), f(f(seed)), etc. The first element (position 0) in the Stream will be the provided seed. For n > 0, the element at position n, will be the result of applying the function f to the element at position n - 1.

The action of applying f for one element happens-before the action of applying f for subsequent elements. For any given element the action may be performed in whatever thread the library chooses.
import java.util.stream.Stream;

public class SampleClass{

  public static void main(String[] args){
  
    Object[] num = Stream.iterate(0,
                   i -> (++i)*i)
                   .limit(6)
                   .toArray();
                        
    for(Object o : num)
      System.out.print(o + " ");
  }
}
  
Result
0 1 4 25 676 458329
We use the limit() to put a limit on the infinite stream.

map() Method

Method form: <R> Stream<R> map(Function<? super T,? extends R> mapper)
Returns a stream consisting of the results of applying the given function to the elements of this stream. This is an intermediate operation.
import java.util.stream.Stream;
import java.util.Arrays;

public class SampleClass{

  public static void main(String[] args){
  
    Integer[] ints = {2,4,6,3,7,9};
    
    Object[] mappedInts = Arrays.stream(ints)
                        .map(v -> v*v)
                        .toArray();
                        
    System.out.println("Array of "
                       +"integers.");
    
    for(Object o : mappedInts)
      System.out.print(o + " ");
  }
}

Result
Array of integers.
4 16 36 9 49 81
There are methods that are associated with map(). These are: mapToDouble(), mapToInt() and mapToLong(). These methods don't return Stream. They return DoubleStream, IntStream and LongStream respectively. These versions of Stream are specialized in primitive wrapper classes.

This example demonstrates mapToInt() method.
import java.util.stream.Stream;
import java.util.Arrays;

public class SampleClass{

  public static void main(String[] args){
  
    Integer[] ints = {2,4,6,3,7,9};
    
    int sum = Arrays.stream(ints)
                    .mapToInt(v -> v*v)
                    .sum();
                        
    System.out.println("Sum: " + sum);
  }
}

Result
Sum: 195
In the example above, we use sum() method. This method returns an int that is the sum of all mapped elements in IntStream.

Mapping is a process of associating an element from a set to another set. Association of elements could be copying an element to another set, generating new elements from elements in the set, etc.

mapMulti() Method

Method form: default <R> Stream<R> mapMulti(BiConsumer<? super T,? super Consumer<R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with multiple elements, specifically zero or more elements. Replacement is performed by applying the provided mapping function to each element in conjunction with a consumer argument that accepts replacement elements. The mapping function calls the consumer zero or more times to provide the replacement elements.

This is an intermediate operation. If the consumer argument is used outside the scope of its application to the mapping function, the results are undefined. This method is similar to flatMap in that it applies a one-to-many transformation to the elements of the stream and flattens the result elements into a new stream.
import java.util.stream.Stream;
import java.util.Arrays;

public class SampleClass{

  public static void main(String[] args){
  
    Integer[][] ints = {{2,4,6},{3,7,9}};
    
    Object[] flatInts = Arrays.stream(ints)
                        .<Integer>mapMulti(
                        (container, consumer) ->
                        {
                          for(Integer i : container)
                            consumer.accept(i*i);
                        })
                        .toArray();
                        
    System.out.println("Flattened array of "
                       +"integers.");
    
    for(Object o : flatInts)
      System.out.print(o + " ");
  }
}

Result
Flattened array of integers.
4 16 36 9 49 81
In the example above, we flatten and map elements without opening additional Stream and additional map operation. We feed the mapped elements to the consumer and the consumer put those elements in a Stream with flattened container. The <Integer> before mapMulti() is an additional type information. According to the documentation:

If a lambda expression is provided as the mapper function argument, additional type information may be necessary for proper inference of the element type <R> of the returned stream. This can be provided in the form of explicit type declarations for the lambda parameters or as an explicit type argument to the mapMulti call.

This is how we achieve the result above using flatMap().
import java.util.stream.Stream;
import java.util.Arrays;

public class SampleClass{

  public static void main(String[] args){
  
    Integer[][] ints = {{2,4,6},{3,7,9}};
    
    Object[] flatInts = Arrays.stream(ints)
                        .flatMap(l -> Arrays.stream(l))
                        .map(v -> v*v)
                        .toArray();
                        
    System.out.println("Flattened array of "
                       +"integers.");
    
    for(Object o : flatInts)
      System.out.print(o + " ");
  }
}
As we can see, on top of Arrays.stream(ints), we add another stream in flatMap() and another intermediate operation which is map().

There are methods that are associated with mapMulti(). These are: mapMultiToDouble(), mapMultiToInt() and mapMultiToLong(). These methods don't return Stream. They return DoubleStream, IntStream and LongStream respectively. These versions of Stream are specialized in primitive wrapper classes.

This example demonstrates mapMultiToInt() method.
import java.util.stream.Stream;
import java.util.stream.IntStream;
import java.util.Arrays;

public class SampleClass{

  public static void main(String[] args){
  
    Integer[][] ints = {{2,4,6},{3,7,9}};
    
    int sum = Arrays.stream(ints)
              .<Integer>mapMultiToInt(
              (container, consumer) ->
              {
                for(Integer i : container)
                  consumer.accept(i*i);
              })
              .sum();
                        
    System.out.println("Sum: " + sum);
  }
}

Result
Sum: 195
mapMulti() is preferable to flatMap() in the following circumstances:
  • When replacing each stream element with a small (possibly zero) number of elements. Using this method avoids the overhead of creating a new Stream instance for every group of result elements, as required by flatMap.
  • When it is easier to use an imperative approach for generating result elements than it is to return them in the form of a Stream.

max() Method

Method form: Optional<T> max(Comparator<? super T> comparator)
This method is a terminal operation that performs a reduction that specializes in finding the maximum element of the stream according to the provided Comparator. This method returns an Optional<T> object.
import java.util.stream.Stream;
import java.util.ArrayList;
import java.util.List;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<String> ar =
    new ArrayList<>();
    
    ar.add("Apple");
    ar.add("melon");
    ar.add("Watermelon");
    ar.add("avocado");
    
    String max = ar.stream()
                 .max(String.CASE_INSENSITIVE_ORDER)
                 .get();
    
    System.out.println("Max value: " + max);
  }
}

Result
Max value: Watermelon
min() Method

Method form: Optional<T> min(Comparator<? super T> comparator)
This method is a terminal operation that performs a reduction that specializes in finding the minimum element of the stream according to the provided Comparator. This method returns an Optional<T> object.
import java.util.stream.Stream;
import java.util.ArrayList;
import java.util.List;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<String> ar =
    new ArrayList<>();
    
    ar.add("Apple");
    ar.add("melon");
    ar.add("Watermelon");
    ar.add("avocado");
    
    String min = ar.stream()
                 .min(String.CASE_INSENSITIVE_ORDER)
                 .get();
    
    System.out.println("Min value: " + min);
  }
}

Result
Min value: Apple
noneMatch() Method

Method form: boolean noneMatch(Predicate<? super T> predicate)
Returns whether no elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated. This is a short-circuiting terminal operation.
import java.util.stream.Stream;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
  
    ArrayList<Integer> ar =
    new ArrayList<>();
    
    ar.add(3);
    ar.add(7);
    ar.add(13);
    ar.add(9);
    ar.add(17);
    
    boolean result = ar.stream()
                    .noneMatch(i -> (i % 2) == 0);
                    
    System.out.println("No number divisible by 2?");
    System.out.println(result);
  }
}

Result
No number divisible by 2?
true
of() Method

This method has two forms.
static <T> Stream<T> of(T t) returns a sequential Stream containing a single element.
static <T> Stream<T> of(T... values) returns a sequential ordered stream whose elements are the specified values.

This example demonstrates of(T... values) method.
import java.util.stream.Stream;

public class SampleClass{

  public static void main(String[] args){
                   
    Stream.of("Apple", "Melon", "Avocado",
              "Watermelon","Avocado")
          .dropWhile(x -> !x.equals("Avocado"))
          .forEach(System.out::println);
  }
}

Result
Avocado
Watermelon
Avocado
This example demonstrates of(T t) method.
import java.util.stream.Stream;

public class SampleClass{

  public static void main(String[] args){
                   
    Stream.of(new String[]{
              "Apple", "Melon", "Avocado",
              "Watermelon","Avocado"})
              .filter(f -> f.startsWith("A"))
              .forEach(System.out::println);
  }
}

Result
Apple
Avocado
Avocado
ofNullable() Method

Method form: static <T> Stream<T> ofNullable(T t)
Returns a sequential Stream containing a single element, if non-null, otherwise returns an empty Stream.
import java.util.stream.Stream;

public class SampleClass{

  public static void main(String[] args){
    
    long count = Stream.ofNullable(null).
                count();
                
    //this will throw an error
    //long count = Stream.of(null).count();
              
    System.out.println("Count: " + count);
  }
}
peek() Method

Method form: Stream<T> peek(Consumer<? super T> action)
Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation.

For parallel stream pipelines, the action may be called at whatever time and in whatever thread the element is made available by the upstream operation. If the action modifies shared state, it is responsible for providing the required synchronization.

This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:
import java.util.stream.Stream;
import java.util.List;
import java.util.stream.Collectors;

public class SampleClass{

  public static void main(String[] args){
    
    List<String> list = 
    Stream.of("one", "two", "three", "four")
    .filter(e -> e.length() > 3)
    .peek(e -> System.out.println("Filtered value: " + e))
    .map(String::toUpperCase)
    .peek(e -> System.out.println("Mapped value: " + e))
    .collect(Collectors.toList());
    
    System.out.println("List elements...");
      for(String str : list)
        System.out.println(str);
  }
}

Result
Filtered value: three
Mapped value: THREE
Filtered value: four
Mapped value: FOUR
List elements...
THREE
FOUR
In cases where the stream implementation is able to optimize away the production of some or all the elements (such as with short-circuiting operations like findFirst, or in the example described in count()), the action will not be invoked for those elements.

reduce() Method

This method has three forms. Let's start with this form:
Optional<T> reduce(BinaryOperator<T> accumulator)

This terminal operation performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any. The accumulator function must be an associative function. Reduction operations can be parallelized without requiring additional synchronization.
import java.util.stream.Stream;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
    
    ArrayList<Integer> ar = 
    new ArrayList<>();
    
    ar.add(2);
    ar.add(4);
    ar.add(6);
    ar.add(184);
    
    int result =
    ar.stream()
    .reduce(
    (curr,next) -> curr*next)
    .get();
               
    System.out.println(result);
  }
}

Result
8832
Next, let's discuss this form:
T reduce(T identity, BinaryOperator<T> accumulator)
import java.util.stream.Stream;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
    
    ArrayList<Integer> ar = 
    new ArrayList<>();
    
    ar.add(4);
    ar.add(6);
    ar.add(184);
    
    int result =
    ar.stream()
    .reduce(Integer.valueOf(2),
    (curr,next) -> curr*next);
               
    System.out.println(result);
  }
}

Result
8832
In the example above, identity is the initial value which is 2. identity is also the default result if the stream is empty. Unlike in the first form, this form doesn't return Optional object.

Next, let's discuss the last form:
<U> U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)
import java.util.stream.Stream;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
    
    ArrayList<Integer> ar = 
    new ArrayList<>();
    
    ar.add(4);
    ar.add(6);
    ar.add(184);
    
    int result =
    ar.parallelStream()
    .reduce(Integer.valueOf(2),
    (x,y) -> x*y,
    (i,j) -> i+j);
               
    System.out.println(result);
  }
}

Result
8832
In the example above, identity is the initial value and default result if the stream is empty. accumulator is a function that multiplies two numbers. combiner combines results from multiple accumulators. The combiner function must be an associative function.

Take note, use parallelStream() if you're processing large arrays in order to take advantage of parallelism. This example is just a mere demonstration of reduce().

skip() Method

Method form: Stream<T> skip(long n)
Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned. This is a stateful intermediate operation.
import java.util.stream.Stream;
import java.util.ArrayList;

public class SampleClass{

  public static void main(String[] args){
    
    ArrayList<Integer> ar = 
    new ArrayList<>();
    
    ar.add(2);
    ar.add(4);
    ar.add(6);
    ar.add(8);
    ar.add(10);
    ar.add(12);
    
    ar.stream()
    .skip(3)
    .forEach(System.out::println);
               
  }
}

Result
8
10
12
takeWhile() Method

Returns, if this stream is ordered, a stream consisting of the longest prefix of elements taken from this stream that match the given predicate. Otherwise returns, if this stream is unordered, a stream consisting of a subset of elements taken from this stream that match the given predicate.

If this stream is ordered then the longest prefix is a contiguous sequence of elements of this stream that match the given predicate. The first element of the sequence is the first element of this stream, and the element immediately following the last element of the sequence does not match the given predicate.
If this stream is unordered, and some (but not all) elements of this stream match the given predicate, then the behavior of this operation is nondeterministic; it is free to take any subset of matching elements (which includes the empty set).
Independent of whether this stream is ordered or unordered if all elements of this stream match the given predicate then this operation takes all elements (the result is the same as the input), or if no elements of the stream match the given predicate then no elements are taken (the result is an empty stream). This is a short-circuiting stateful intermediate operation.
import java.util.stream.Stream;
import java.util.Arrays;
import java.util.List;

public class SampleClass{

  public static void main(String[] args){
  
    String[] ar = {"Apple", "Melon", "Avocado",
                   "Watermelon","Avocado"};
    
    List<String> list =
    Arrays.stream(ar)
          .takeWhile(x -> !x.equals("Avocado"))
          .toList();
               
    System.out.println("Elements...");
    for(String str : list)
      System.out.print(str + " ");
  }
}

Result
Elements...
Apple Melon
In the example above, we see that as long as the return value of predicate in takeWhile() is true, evaluated elements that is evaluated as true will be included in the Stream that will be returned by takeWhile(). If the return value of predicate in takeWhile() is false, the evaluated element that is evaluated as false and the subsequent elements will be dropped.