Java Stream Archives - Huong Dan Java https://huongdanjava.com/tag/java-stream-en Java development tutorials Sun, 03 Jan 2021 21:59:29 +0000 en-US hourly 1 https://wordpress.org/?v=6.9.4 https://huongdanjava.com/wp-content/uploads/2018/01/favicon.png Java Stream Archives - Huong Dan Java https://huongdanjava.com/tag/java-stream-en 32 32 Group by using Stream and Collectors in Java https://huongdanjava.com/group-by-using-stream-and-collectors-in-java.html https://huongdanjava.com/group-by-using-stream-and-collectors-in-java.html#respond Fri, 02 Mar 2018 06:37:16 +0000 https://huongdanjava.com/?p=7079 In SQL, the GROUP BY statement returns the set of records having the same value in particular criteria. For example, you have a table that contains student information, each student coming from a different country. Use the GROUP BY statement according to national criteria, you… Read More

The post Group by using Stream and Collectors in Java appeared first on Huong Dan Java.

]]>
In SQL, the GROUP BY statement returns the set of records having the same value in particular criteria. For example, you have a table that contains student information, each student coming from a different country. Use the GROUP BY statement according to national criteria, you can know the number of students from some countries. Similarly, from version 8, Java also supports us by the group by function. In this tutorial, I will show you how to group by using Stream and Collectors in Java.

For example, I have a list of students with the following information:

package com.huongdanjava.javaexample;

public class Student {

	private String name;
	private String country;

	public Student(String name, String country) {
		this.name = name;
		this.country = country;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((country == null) ? 0 : country.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (country == null) {
			if (other.country != null)
				return false;
		} else if (!country.equals(other.country))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Student{" + "name='" + name + '\'' + ", country='" + country + '\'' + '}';
	}
}

List<Student> names = Arrays.asList(
    new Student("Khanh", "VN"),
    new Student("Peter", "US"),
    new Student("Thanh", "VN"),
    new Student("Khanh", "VN"));

Now, I need to group the above student list by country and count the number of students in each country.

To do this, we will use the collect() method in the Stream object with the groupingBy() static method in the Java Collectors object.

For example, if we need a group of students by country, we would like to code as follows:

Map<String, List<Student>> result = names.stream()
    .collect(Collectors.groupingBy(Student::getCountry));

Result:

Group by using Stream and Collectors in Java

In the code above, the parameter of the groupingBy() method is the same as the criteria in the SQL. If you want to group by student name then you can replace Student::getCountry with Student::getName.

As you can see, by default after the group is finished, any element that has the same criteria falls into a List object, we can change this by passing another parameter to the groupingBy() method of the Collectors object. For example, now that I want the elements with the same criteria to be in a Set object, I would like to code as follows:

Map<String, Set<Student>> result = names.stream()
    .collect(Collectors.groupingBy(Student::getCountry, Collectors.toSet()));

Result:

Group by using Stream and Collectors in Java

Also, if after grouping, you want to count the number of students in each country, then use the groupingBy method as follows:

Map<String, Long> result = names.stream()
    .collect(Collectors.groupingBy(Student::getCountry, Collectors.counting()));

Here, I used another method of the Collectors object called counting() to count the number of students in each country that I wanted.

Result:

Group by using Stream and Collectors in Java

 

The post Group by using Stream and Collectors in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/group-by-using-stream-and-collectors-in-java.html/feed 0
stream() method of Optional object in Java https://huongdanjava.com/stream-method-optional-object-java.html https://huongdanjava.com/stream-method-optional-object-java.html#respond Tue, 06 Feb 2018 07:11:57 +0000 https://huongdanjava.com/?p=6580 This method is supported since Java 9. This method is used to create a new Stream object from an Optional object in Java. If the Optional object contains a value, this method will return the Stream object containing that value, otherwise, it returns an empty… Read More

The post stream() method of Optional object in Java appeared first on Huong Dan Java.

]]>
This method is supported since Java 9.

This method is used to create a new Stream object from an Optional object in Java.

If the Optional object contains a value, this method will return the Stream object containing that value, otherwise, it returns an empty Stream object.

For example:

package com.huongdanjava.javaexample;

import java.io.IOException;
import java.util.Optional;
import java.util.stream.Stream;

public class Example {

	public static void main(String[] args) throws IOException {
		String s = "Khanh";

		Optional<String> opt = Optional.ofNullable(s);
		Stream<String> stream = opt.stream();
		stream.forEach(System.out::println);
	}
}

Result:

stream() method of Optional object in Java

In the case where we have a List of Optional objects, one of them is empty, the stream() method of the Optional object can help us remove these Optional empty objects.

For example:

package com.huongdanjava.javaexample;

import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

public class Example {

	public static void main(String[] args) throws IOException {
		List<Optional<String>> names = List.of(
			Optional.of("Khanh"), 
			Optional.empty(), 
			Optional.of("Quan"));

		Stream<String> stream = names.stream().flatMap(Optional::stream);
		stream.forEach(System.out::println);
	}
}

You can refer to the flatMap() method of the Stream object here.

Result:

stream() method of Optional object in Java

 

The post stream() method of Optional object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/stream-method-optional-object-java.html/feed 0
Method iterate() of Stream object in Java https://huongdanjava.com/method-iterate-stream-object-java.html https://huongdanjava.com/method-iterate-stream-object-java.html#respond Sun, 01 Oct 2017 12:53:52 +0000 https://huongdanjava.com/?p=4475 In Java 8, the iterate() method has been introduced and it has only two parameters and will help us to create an infinite stream. Content: [crayon-69bb6eabb9b3d872283006/] Example: [crayon-69bb6eabb9b40455357467/] When running the above example, you will see that a Stream object contains endless numbers beginning at… Read More

The post Method iterate() of Stream object in Java appeared first on Huong Dan Java.

]]>
In Java 8, the iterate() method has been introduced and it has only two parameters and will help us to create an infinite stream.

Content:

public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)

Example:

package com.huongdanjava.javastream;

import java.util.stream.Stream;

public class Example {

	public static void main(String[] args) {
		Stream.iterate(1, i -> i + 1).forEach(System.out::println);
	}
}

When running the above example, you will see that a Stream object contains endless numbers beginning at 1.

With Java 9, the iterate() method has improved by adding another parameter, the Predicate interface, which allows us to stop these endless numbers based on the conditions we define with the Predicate interface.

Content:

public static<T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)

Example:

package com.huongdanjava.javastream;

import java.util.stream.Stream;

public class Example {

	public static void main(String[] args) {
		Stream.iterate(1, i -> i < 10, i -> i + 1).forEach(System.out::println);
	}
}

Result:

Method iterate() of Stream object in Java


The post Method iterate() of Stream object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/method-iterate-stream-object-java.html/feed 0
Method ofNullable() of Stream object in Java https://huongdanjava.com/method-ofnullable-stream-object-java.html https://huongdanjava.com/method-ofnullable-stream-object-java.html#respond Sun, 01 Oct 2017 12:51:19 +0000 https://huongdanjava.com/?p=4469 This method was added from Java 9. [crayon-69bb6eabb9cb3921060138/] This method will return the Stream object of an element in case this element is not null; if it is null, it returns an empty Stream. Example: [crayon-69bb6eabb9cb5990659370/] When you run the above code, it will print… Read More

The post Method ofNullable() of Stream object in Java appeared first on Huong Dan Java.

]]>
This method was added from Java 9.

static<T> Stream<T> ofNullable(T t)

This method will return the Stream object of an element in case this element is not null; if it is null, it returns an empty Stream.

Example:

package com.huongdanjava.javaexample;

import java.util.stream.Stream;

public class Example {

	public static void main(String[] args) {
		String s = null;
		Stream.ofNullable(s).forEach(System.out::println);
	}
}

When you run the above code, it will print nothing in the console. But if you edit the variable s, not null:

package com.huongdanjava.javaexample;

import java.util.stream.Stream;

public class Example {

	public static void main(String[] args) {
		String s = "Khanh";
		Stream.ofNullable(s).forEach(System.out::println);
	}
}

then the result will be:

Method ofNullable() of Stream object in Java

 

The post Method ofNullable() of Stream object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/method-ofnullable-stream-object-java.html/feed 0
Method dropWhile() of Stream object in Java https://huongdanjava.com/method-dropwhile-stream-object-java.html https://huongdanjava.com/method-dropwhile-stream-object-java.html#respond Sun, 01 Oct 2017 12:46:51 +0000 https://huongdanjava.com/?p=4467 This method was added from Java 9. [crayon-69bb6eabb9e25285440476/] This method also has the parameter Predicate interface and its function is the opposite of the takeWhile() method. This method also passes each element in your Stream object from left to right and ignores all elements that… Read More

The post Method dropWhile() of Stream object in Java appeared first on Huong Dan Java.

]]>
This method was added from Java 9.

default Stream<T> dropWhile(Predicate<? super T> predicate)

This method also has the parameter Predicate interface and its function is the opposite of the takeWhile() method. This method also passes each element in your Stream object from left to right and ignores all elements that satisfy the condition. Once the condition is no longer fulfilled, it will take all the remaining elements to return.

Example:

package com.huongdanjava.javastream;

import java.util.stream.Stream;

public class Example {

	public static void main(String[] args) {
		Stream.of(3,2,4,1,4,6,7,8,9,10)
			.dropWhile(i -> i < 5)
			.forEach(System.out::println);
	}
}

In the above example, the dropWhile() method will ignore all elements smaller than 5 and when an element larger than 5, it will return all the remaining elements including this element.

Result:

Method dropWhile() of Stream object in Java


The post Method dropWhile() of Stream object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/method-dropwhile-stream-object-java.html/feed 0
Method takeWhile() of Stream object in Java https://huongdanjava.com/method-takewhile-of-stream-object-in-java.html https://huongdanjava.com/method-takewhile-of-stream-object-in-java.html#respond Sun, 01 Oct 2017 12:44:03 +0000 https://huongdanjava.com/?p=4464 This method was added from Java 9. [crayon-69bb6eabb9fa3051922462/] The parameter of this method is the Predicate interface and this method takes the elements in your Stream object from left to right, until the condition of the Predicate object is no longer fulfilled. Example: [crayon-69bb6eabb9fa5851618483/] In… Read More

The post Method takeWhile() of Stream object in Java appeared first on Huong Dan Java.

]]>
This method was added from Java 9.

default Stream<T> takeWhile(Predicate<? super T> predicate)

The parameter of this method is the Predicate interface and this method takes the elements in your Stream object from left to right, until the condition of the Predicate object is no longer fulfilled.

Example:

package com.huongdanjava.javastream;

import java.util.stream.Stream;

public class Example {

	public static void main(String[] args) {
		Stream.of(1,2,3,4,5,6,7,8,9,10)
			.takeWhile(i -> i < 5)
			.forEach(System.out::println);
	}
}

In the above example, the condition for getting the elements from left to right is that they must be less than 5. When the element is greater than 5, the method will stop and returns the result.

Result:

Method takeWhile() of Stream object in Java


The post Method takeWhile() of Stream object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/method-takewhile-of-stream-object-in-java.html/feed 0
Using flatMap() method of Stream object in Java https://huongdanjava.com/using-flatmap-method-of-stream-object-in-java.html https://huongdanjava.com/using-flatmap-method-of-stream-object-in-java.html#respond Sat, 05 Aug 2017 23:26:54 +0000 https://huongdanjava.com/?p=3545 When working with Stream in Java, sometime we can have a Stream with datatype of a List, Set or Array of object. For example: [crayon-69bb6eabba107818426606/] Here, we have List of List of String object and when convert into Stream object, we have Stream of List… Read More

The post Using flatMap() method of Stream object in Java appeared first on Huong Dan Java.

]]>
When working with Stream in Java, sometime we can have a Stream with datatype of a List, Set or Array of object. For example:

List<String> students1 = new ArrayList<>();
students1.add("Khanh");

List<String> students2 = new ArrayList<>();
students2.add("Thanh");
students2.add("Dung");

List<List<String>> students = Arrays.asList(students1, students2);

Stream<List<String>> stream = students.stream();

Here, we have List of List of String object and when convert into Stream object, we have Stream of List of String object.

When that, if we want to manipulate on this Stream object like filter, then we cannot do that. For example:

Using flatMap() method of Stream object in Java

To resolve this problem, we can use flatMap() method before the manipulation you need. With flatMap() method, we can flatten our Stream of List, Set or Array object into a simple one like Stream of object. For example:

List<String> students1 = new ArrayList<>();
students1.add("Khanh");

List<String> students2 = new ArrayList<>();
students2.add("Thanh");
students2.add("Dung");

List<List<String>> students = Arrays.asList(students1, students2);

Stream<List<String>> stream = students.stream();
Stream<String> flatMap = stream.flatMap(l -> l.stream());

Now, we can use flatMap() method to resolve our problem.

Using flatMap() method of Stream object in Java

The post Using flatMap() method of Stream object in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/using-flatmap-method-of-stream-object-in-java.html/feed 0
Filter a Map using Stream and Lambda Expression in Java https://huongdanjava.com/filter-a-map-using-stream-and-lambda-expression-in-java.html https://huongdanjava.com/filter-a-map-using-stream-and-lambda-expression-in-java.html#respond Thu, 03 Aug 2017 22:12:20 +0000 https://huongdanjava.com/?p=3534 To filter a Map using Stream and Lambda Expression in Java, we will use the filter() method of Stream object which will be retrieved from Entry object of Map object with Lambda Expression as filter a List. How is it in details? Let learn together in… Read More

The post Filter a Map using Stream and Lambda Expression in Java appeared first on Huong Dan Java.

]]>
To filter a Map using Stream and Lambda Expression in Java, we will use the filter() method of Stream object which will be retrieved from Entry object of Map object with Lambda Expression as filter a List. How is it in details? Let learn together in this tutorial.

Example, I have the following Map object as below:

Map<String, Integer> studentMap = new HashMap<>();
studentMap.put("Khanh", 31);
studentMap.put("Thanh", 25);
studentMap.put("Dung", 35);

Before Java 8, to filter this Map and only get the age of Khanh, we can write the code as below:

int age = 0;
for (Map.Entry<String, Integer> entry : studentMap.entrySet()) {
    if ("Khanh".equals(entry.getKey())) {
        age = entry.getValue();
    }
}

Result:

Filter a Map using Stream and Lambda Expression in Java

Since Java 8, we can re-write this code as below:

Integer result = studentMap.entrySet().stream()
    .filter(map -> "Khanh".equals(map.getKey()))
    .map(map -> map.getValue())
    .findFirst()
    .get();

System.out.println(result);

Result:

Filter a Map using Stream and Lambda Expression in JavaHere you can also filter a Map and return a new Map as below:

Map<String, Integer> result = studentMap.entrySet().stream()
    .filter(map -> "Khanh".equals(map.getKey()))
    .collect(Collectors.toMap(m -> m.getKey(), m -> m.getValue()));

System.out.println(result);

Result:

Filter a Map using Stream and Lambda Expression in Java

 

The post Filter a Map using Stream and Lambda Expression in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/filter-a-map-using-stream-and-lambda-expression-in-java.html/feed 0
Sort a Map using Stream and Collectors in Java https://huongdanjava.com/sort-a-map-using-stream-and-collectors-in-java.html https://huongdanjava.com/sort-a-map-using-stream-and-collectors-in-java.html#respond Wed, 02 Aug 2017 21:38:43 +0000 https://huongdanjava.com/?p=3504 In this tutorial, I will show you how to order elements in a Map object using the Stream object and the Collectors object in Java by key and by value. For example, we have a Map object like this: [crayon-69bb6eabba4c9784075779/] Prior to Java 8, to… Read More

The post Sort a Map using Stream and Collectors in Java appeared first on Huong Dan Java.

]]>
In this tutorial, I will show you how to order elements in a Map object using the Stream object and the Collectors object in Java by key and by value.

For example, we have a Map object like this:

Map<String, Integer> studentMap = new HashMap<>();
studentMap.put("Khanh", 31);
studentMap.put("Thanh", 25);
studentMap.put("Dung", 35);

Prior to Java 8, to sort the elements of this Map object by key, we could use the Collections.sort() static method of the Collections class:

List<Map.Entry<String, Integer>> students = new ArrayList<Map.Entry<String, Integer>>();
students.addAll(studentMap.entrySet());

Collections.sort(students, new Comparator<Map.Entry<String, Integer>>() {
    @Override
    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
        return o1.getKey().compareTo(o2.getKey());
    }
});

Result:

Sort a Map using Stream and Collectors in Java

Do the same if you want to use the sort() static method of the Collections class to sort the elements in the Map object by value.



From Java 8 onwards, you have another way to use the Stream object with the Collectors object.

We will create a new Stream object from the Map object and then use the sorted() and collect() methods of this Stream object to sort.

For example, we need to order the elements of the Map object by key, we will code as follows:

Map<String, Integer> students = studentMap.entrySet()
    .stream()
    .sorted((o1, o2) -> o1.getKey().compareTo(o2.getKey()))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

Here, the sorted() method acts as an intermediate operation in the Stream pipeline. The parameter of this method is a Comparator object that allows us to define what criteria to sort. You can also use the static comparingByKey() method of the Map.Entry class to sort by key as follows:

Map<String, Integer> students = studentMap.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByKey())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

The collect() method will act as a terminal operation in the Stream pipeline. The parameter of this method is a Collectors object and we will use the Collectors object’s toMap() method to construct a new Map object after sorting.

The Collectors object’s toMap() method has some overload methods:

toMap(Function keyMapper, Function valueMapper)

toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)

toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier)

Where the first and second parameters of the toMap() method are instances of the Function interface used to generate keys and values for the new Map object.

The third parameter of the toMap() method is an optional parameter that is used in case the key of the new Map object has duplicate values. Using the BinaryOperator object, we can select the value of these duplicate keys, avoiding the IllegalStateException. In the above example, (oldValue, newValue) -> oldValue means that in case the key is duplicated, we will get the value of the previous key.

The final parameter of the toMap() method is also an optional parameter, which allows us to define a new Map object as a class instance. By default, if you do not use this parameter, then the class will be HashMap.

The result of this example is as follows:

Sort a Map using Stream and Collectors in Java

To order elements in a Map object by value, we can use the static comparingByValue() method of the Map.Entry object:

Map<String, Integer> students = studentMap.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

Here, I use the reverseOrder() static method of the Comparator class to sort these values descending.

Result:

Sort a Map using Stream and Collectors in Java

 

The post Sort a Map using Stream and Collectors in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/sort-a-map-using-stream-and-collectors-in-java.html/feed 0
Introduce about Stream in Java https://huongdanjava.com/introduce-about-stream-in-java.html https://huongdanjava.com/introduce-about-stream-in-java.html#respond Thu, 27 Jul 2017 03:37:04 +0000 https://huongdanjava.com/?p=3409 Stream is a new Java object, was introduced from Java 8. It helps us can manipulate on collections and arrays easier and more efficient. So what is it? In this article, I will introduce with you all about the Stream in Java. First, consider the… Read More

The post Introduce about Stream in Java appeared first on Huong Dan Java.

]]>
Stream is a new Java object, was introduced from Java 8. It helps us can manipulate on collections and arrays easier and more efficient. So what is it? In this article, I will introduce with you all about the Stream in Java.

First, consider the following example:

package com.huongdanjava.example;

import java.util.Arrays;
import java.util.List;

public class Example {

	public static void main(String[] args) {
		List<String> names = Arrays.asList("Khanh", "Thanh", "Dung");

		names.stream()
			.filter(s -> s.startsWith("K"))
			.forEach(System.out::println);
	}
}

In this example, we have a List of the String object. From this List object, we convert it into the object of the Stream, then use this Stream object to filter the String starting with the “K” character, and finally print the String object beginning with “K” to the console.

Result:

Introduce about Stream in Java

Obviously, as you can see, using Stream with Lambda Expression makes our code easier to understand and read.

In the code above, we take the Stream object from the Collection object, would you feel like Stream is a Collection? It’s not, Stream is not a Collection.

Simply, Stream is a collection and array wrapper. It wraps an existing collection and other data sources to support manipulation on that collections or data sources using Lambda Expression. So, you just need specify what you want to do, and how to do it, Stream will worry about that.

Characteristics of Stream include:

  • Stream perfect support for Lambda Expression.
  • Stream does not contain collection or array elements.
  • Stream is an immutable object.
  • The stream is not reusable, meaning that once it is used, we can not call it again for using.
  • We cannot use the index to access elements in the Stream.
  • Stream supports parallel manipulation of elements in a collection or array.
  • Stream supports lazy manipulation, as needed, new operations are performed.

To do this, most operations with Stream return a new Stream, which creates a chain containing a series of operations to perform the operation in the most optimal way. This chain is also called a pipeline.

There are three main steps to create a pipeline for Stream:

Create a new Stream.

The Stream interface in the java.util.stream package is the interface that represents a Stream. This interface only works with the data type is object.

With primitives, you can use Stream objects for those types of primitives, such as IntStream, LongStream, or DoubleStream.

We have many ways to create a new Stream:

Create a new Stream from a collection

Eg:

List<String> names = Arrays.asList("Khanh", "Thanh", "Dung");
Stream<String> stream = names.stream();

Create new Stream from certain values using the Stream interface.

Eg:

Stream<String> stream = Stream.of("Khanh", "Thanh", "Dung");

Create Stream from an array.

Eg:

String[] names = { "Khanh", "Thanh", "Dung" };
Stream<String> stream = Stream.of(names);

Use 0 or more intermediate operations to convert an original Stream into a new one.

Stream has many intermediate operations to manipulate Stream, as shown at the beginning of the article we used:

Stream<String> stream = Stream.of("Khanh", "Thanh", "Dung");
stream.filter(s -> s.startsWith("K")).distinct();

Most intermediate operations return a new Stream object.

The important thing that you all need to know is even though we define many intermediate operations but they do not perform these operations immediately. Only when the terminal operation is called, these intermediates will be performed.

Use of terminal operation to retrieve results or a side-effect from defined intermediate operations.

You can easily to determine what is an intermediate operation, what is a terminal operation because the terminal operation will return a void or non-stream object.

After the terminal operation is called, Stream will no longer be available. If you want to use it again, you must create a new Stream from the collection or array you want.


The post Introduce about Stream in Java appeared first on Huong Dan Java.

]]>
https://huongdanjava.com/introduce-about-stream-in-java.html/feed 0