Collectors toMap

Java-Collectors toMap

Collectors toMap The Collectors class provides a large number of static methods for common collectors. The toMap( ) method of the collectors is used to collect stream elements into a Map.  The toMap( ) method has three forms. The first is: If the mapped keys contain duplicates (according to Object.equals(Object)), an IllegalStateException is thrown when the collection … Read more…

Using Collector for Collection

Java-Using Collector for Collection

Using Collector for Collection The stream API provides the another form of collect( ) method. This method is used to obtain a collection from a stream using Collector interface. It has the following form: Here, R specifies the type of the result, and T specifies the element type of the invoking stream. The internal accumulated type … Read more…

Collection From a Stream

Java-Collection From a Stream

Collection From a Stream The stream API provides the collect( ) method. This method is used to obtain a collection from a stream. The ability to move data from a collection to a stream, and then back to a collection again is a very powerful attribute of the stream API. It gives you the ability … Read more…

Another Version of Reduce

Java-Another Version of Reduce

Another Version of Reduce Suppose you have a stream of objects and want to form the sum of some property, such as all lengths in a stream of strings. For example: In this case, you can’t use the simple form of reduce. It requires a function (T, T) -> T, with the same types for the … Read more…

Stream to Primitive Stream

Java-Stream to Primitive Stream

Stream to Primitive Stream The Stream class provides three methods that return a primitive stream from Stream. These three methods are: Consider the following program, it first creates an Stream of PlayerData. It then uses mapToInt( ) and mapToDouble( ) to create an IntStream and DoubleStream that are contains the each player weight and height. The … Read more…

Stream to Array

Java-Stream to Array

Stream to Array If you want to get the stream elements to an array, use the toArray( ) method. The toArray( ) method of Stream is used to get an array of the stream elements. This method has two forms. First: Since it is not possible to create a generic array at runtime, the expression stream.toArray() returns … Read more…