Skip to main content

Posts

Showing posts from September, 2021

Java Stream - Convert a Stream to List

In this tutorial you’ll see how to convert a Stream to list using collector method and utility methods like toList() and toCollection() of Collectors class in Java Stream API . 1. A simple example to collect Stream elements into an ArrayList . import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamToList { public static void main(String[] args) { Stream<String> streamElem = Stream.of("A", "B", "C", "D"); List<String> listFromStream = streamElem.collect(Collectors.toList()); System.out.println(listFromStream.getClass().getName()); System.out.println("Elements in the list- " + listFromStream); } } Output java.util.ArrayList Elements in the list- [A, B, C, D] As you can see type of the List returned is ArrayList. 2. If you want to convert the Stream into a LinkedList then you can use Collectors.toCollection() method. public class StreamToLi

Java Stream - Get Last Element

In this tutorial we’ll see what options are there to get the last element of the stream using the Java Stream API . 1. Using reduce() method reduce method in the Java Stream API is used to perform a reduction on the elements of the stream so that the stream is reduced to a single value. Thus it can be used to reduce the stream to a last value. import java.util.Arrays; import java.util.List; public class StreamLastDemo { public static void main(String[] args) { List<Integer> numList = Arrays.asList(6, 10, 5, 6, 7, 8, 12); int lastElement = numList.stream().reduce((f, s) -> s).orElse(-1); System.out.println("Last element in the Stream- " + lastElement); } } Output Last element in the Stream- 12 2. Using skip() method You can also use skip method to skip to the last element and then return that element. This approach is not very efficient though. public class StreamLastDemo { public static void main(String[] args) { List<Integer&

flatMap() in Java Stream

When you use map operations in Java Stream resulting stream is obtained by applying the given function to all the elements of this stream. Java Stream API also provides a flatMap() method that apart from applying the given function to all the elements of this stream, flattens the resulting elements too so that all the nested elements are at the same level. flatMap is an intermediate operation. flatMap method signature <R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper) Here mapper is a non-interfering, stateless function applied to each element of the stream. R is the element type of the new stream. flatMap Java examples Let’s try to understand with few examples how flatMap() flattens the structure and how it helps. Suppose there is an ArrayList that contains ArrayLists in turn and you want to count the total number of elements in the list. If you use map function then you will get the number of elements as 2 beca

map() Function in Java With Examples

In this post we’ll see examples of map() function in Java Stream API that is used to apply some transformation to the elements in a stream. When you use a map operation a new stream is returned consisting of the resultant elements after applying the given function to all the elements of source stream. Generalized map() function in java.util.stream.Stream interface is- <R> Stream<R> map(Function<? super T,? extends R> mapper) Here R is the element type of the new interface. mapper is a non-interfering, stateless function applied to each element, mapper is of type Function which is a functional interface and can be implemented as a lambda expression . Apart from the generalized map() function there are also methods mapToInt() , mapToLong() , and mapToDouble() returning IntStream, LongStream and DoubleStream respectively which are specialized primitive type streams for these primitive data types . In the primitive type streams there is also a mapToObj(

Java Stream Collectors.teeing() Examples

In this tutorial we’ll see how to use Collectors.teeing() method which is added in Java 12 to the Collectors class in the Java Stream API . Collectors.teeing() method The teeing() method let you create a composite of two Collectors and there is also a third argument; a merging function. Every element passed to the method is processed by both downstream collectors, then their results are merged using the specified merge function into the final result. Method syntax public static <T,R1,R2,R> Collector<T,?,R> teeing(Collector<? super T,?,R1> downstream1, Collector<? super T,?,R2> downstream2, BiFunction<? super R1,? super R2,R> merger) Here parameters are- downstream1 - the first downstream collector downstream2 - the second downstream collector merger - the function which merges two results into the single one Collectors.teeing() Java examples 1. Getting count and sum of elements in a List using Collectors.teeing function. By passin

Java Stream Collectors.partitioningBy() Examples

In this tutorial we’ll see examples of Collectors.partitioningBy() method which is part of the Collectors class in the Java Stream API. Collectors.partitioningBy() method partitions the input elements according to a passed Predicate (which defines the condition for partitioning), and organizes them into a Map<Boolean, List> with values assigned to two keys "false" and "true" based on whether the input element passes the condition or not. There are two overloaded Collectors.partitioningBy() methods- 1. Collector<T,?,Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate) - Partitions the input elements according to the passed Predicate. 2. Collector<T,?,Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate, Collector<? super T,A,D> downstream) - In this method along with a Predicate another Collector is also passed as an argument that reduces the values in each partition, and or

Java Stream Collectors.groupingBy() Examples

In this tutorial we’ll see some examples of Collectors.groupingBy() method in Java Stream API. Collectors.groupingBy() method works similarly to "group by" statement in SQL which groups the elements as per the specified columns. This method also groups the elements according to the passed property and returns grouped result as a Map. There are three overloaded Collectors.groupingBy() method- Collector<T,?,Map<K,List>> groupingBy(Function<? super T,? extends K> classifier) - This method groups elements according to a classification function and returns the results in a Map. The collector produces a Map<K, List> where key specifies a group and List contains the elements which map to the associated key Collector<T,?,Map<K,D>> groupingBy(Function<? super T,? extends K> classifier, Collector<? super T,A,D> downstream) - In this groupingBy() method first elements are grouped according to a passed classification function

Java Stream Collectors.joining() Method With Examples

In this tutorial we’ll see how to use Collectors.joining() method to concatenate the input elements into a String. It is a handy utility method provided by the Collectors class in Java Stream API to quickly convert array elements or elements in a collection to String. There are three overloaded Collectors.joining() method- Collector<CharSequence,?,String> joining() - Concatenates the input elements into a String, in encounter order. Collector<CharSequence,?,String> joining(CharSequence delimiter) - In this method you can also pass a delimiter, it concatenates the input elements, separated by the specified delimiter, in encounter order. Collector<CharSequence,?,String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) - This method concatenates the input elements, separated by the specified delimiter, with the specified prefix and suffix, in encounter order. Collectors.joining() Java Stream API examples 1. In this example w

Java Stream Sort on Multiple Fields

In this tutorial you’ll see how to sort stream of objects on multiple fields. Sort stream of objects on multiple fields To sort a stream of objects on multiple fields you need to use two methods- 1. Stream<T> sorted(Comparator<? super T> comparator) - sorts the elements of this stream according to the provided Comparator. 2. Since sorting is to be done on multiple fields for that you can compose several Comparators using thenComparing(Comparator<? super T> other) method. Comparator.comparing(COMPARISON_LOGIC) .thenComparing(COMPARISON_LOGIC); Java Stream sorting with multiple fields example For the example we’ll use the object of User class which has two fields name and age. public class User { private String name; private int age; User(String name, int age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() {

Java Stream sorted() With Examples

In this tutorial we’ll see how to use Java Stream sorted() method with the help of few examples. Table of contents Syntax of sorted() method in Java Stream API Sort List of integers in natural order Sort List of integers in reverse order Sort List of Strings Sorting List of custom objects Sorting a Set using Java Stream sorted() method Sorting a Map using Java Stream sorted() method Syntax of sorted() method in Java Stream API There are two variants of sorted() method. Stream<T> sorted() - Used to sort the elements of the stream according to natural order. If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed. Stream<T> sorted(Comparator<? super T> comparator) - Used to sort the elements of the stream according to the provided Comparator. sorted() in Java Stream is a stateful intermediate operation which means it may incorporate state from p

Java Stream distinct() With Examples

Java Stream distinct() method is used to get the distinct elements of the stream. It means this method filters out the duplicate elements. Syntax of the distinct method Syntax of the distinct() method in the Java Stream API is as given below- Stream<T> distinct() Method returns a new stream consisting of the distinct elements. For element comparison distinct() method uses the equals() method. distinct() method is a stateful intermediate operation which means it may incorporate state from previously seen elements when processing new elements. If there are duplicate elements in an ordered stream the element appearing first in the encounter order is preserved. For unordered streams, no stability guarantees are made. Java Stream distinct() examples 1. Using distinct() method to remove duplicate elements from a List of integers. import java.util.List; public class DistinctDemo { public static void main(String[] args) { // Till Java 8 //List&l

Java Stream max() and min() With Examples

Java Stream API provides two methods max() and min() where- max() - Returns the maximum element of this stream according to the provided Comparator. min() - Returns the minimum element of this stream according to the provided Comparator. Table of contents Java Stream max() method max() method Java examples Java Stream min() method min() method Java examples Java Stream max() method Syntax of the max() method in Java Stream API is as given below Optional<T> max(Comparator<? super T> comparator) Method returns an Optional describing the maximum element of this stream, or an empty Optional if the stream is empty. This is a terminal operation. max() method Java examples 1. In this simple example we’ll use a List as a source of Stream and get the maximum element of the List. import java.util.Arrays; import java.util.List; import java.util.Optional; public class MaxDemo { public static void main(String[] args) { // Till Java 8