Java 8 Stream API collect() method Example





Hey guys, in this post we will discuss the Java 8 Stream API collect() method, we will also look at some of the examples.

Overview


  • Java stream collect() method is used to perform mutable fold operations means repackaging elements to some data structures and applying some additional logic, concatenating them, etc. on data elements held in a stream object.
  • collect() processes the stream elements and then accumulate them into a mutable result container. once the elements are processed, a combining function merges all the result containers to create the result.
  • Stream.collect() is a terminal method.

Two variant of collect method


  • collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)
  • collect(Collector collector)

Here, the supplier is a function that creates a new mutable result container. For the parallel execution, this function may be called multiple times and it must return a fresh value each time.

the accumulator is a stateless function that must fold an element into a result container.

combiner is a stateless function that accepts two partial result containers and merges them, which must be compatible with the accumulator function.

Example 1: collect() method with 3 parameters

import java.util.List;

public class UserInput {
	
	public static void main(String[] args) {
		
		List alphabets = List.of("a", "b", "c", "d", "e", "f");
		StringBuilder result = alphabets.stream()
                .collect(StringBuilder::new, (x, y) -> x.append(y),
                (a, b) -> a.append(",").append(b));

		System.out.println(result.toString());

    
		StringBuilder result1 = alphabets.parallelStream()
                .collect(StringBuilder::new, (x, y) -> x.append(y),
                (a, b) -> a.append(",").append(b));
		
		System.out.println(result1.toString());
	}
}

Output:

abcdef
a,b,c,d,e,f

supplier: The supplier function is returning a new StringBuilder object in every call

accumulator: The accumulator function is appending the list string element to the StringBuilder instance.

combiner: The combiner function is merging the StringBuilder instances. The instance is merged with each other with a comma between them.

In the above example, we use a parallel stream of strings. So, the elements are processed parallelly and there are multiple instances of StringBuilder that are being merged by the combiner function.

Example 2: collect() method with a single parameter. get Set from List

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class UserInput {
	
	public static void main(String[] args) {
		
		List laptops = List.of("Dell", "HP", "Macbook Air", "Acer", "HP", "Dell");
		
		Set unique = laptops.stream().collect(Collectors.toSet());
		
		System.out.println(unique);
	}
}

Output:

[Acer, Dell, HP, Macbook Air]

Example 3: collect() method with Collectors. get Map from List

  • The map contains key and value pairs but Stream contains just one element, so we need to provide the logic to extract key and value object from Stream.




  • Like, if we have a Stream of String then we can create a Map where the key is String itself and value is their length.
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class UserInput {
	
	public static void main(String[] args) {
		
		List doubles = List.of(22.3, 33.3, 44.4, 55.5, 66.6, 77.7);
		
		Collection result = doubles.stream()
					           .collect(Collectors.toCollection(LinkedList::new));
		
		System.out.println(result);
	}
}

Output:

{Acer=4, Dell=4, HP=2, Macbook Air=11}

So far we have discussed two methods but there are so many methods of collectors class, let’s discuss one by one

Usage of Collectors.toCollection()


When using toSet() and toList() collectors, you can’t make any assumptions about their implementations. If you want to use a custom implementation, you will need to use the toCollection() collector with a provided collection of your choice

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class UserInput {
	
	public static void main(String[] args) {
		
		List doubles = List.of(22.3, 33.3, 44.4, 55.5, 66.6, 77.7);
		
		Collection result = doubles.stream()
                                                   .collect(Collectors.toCollection(LinkedList::new));
		
		System.out.println(result);
	}
}

Output:

[22.3, 33.3, 44.4, 55.5, 66.6, 77.7]

Usage of collectingAndThen()


collectingAndThen() is a special collector that allows performing another action on a result straight after collecting ends.

Let’s collect stream elements to a set instance and then convert the result into an immutableSet instance.

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class UserInput {
	
	public static void main(String[] args) {
		
		List numbers = List.of(98, 99, 98, 85, 88, 85);
		
		Set result = numbers.stream()
					     .collect(Collectors.collectingAndThen(Collectors.toSet(), Collections::unmodifiableSet));
		
		System.out.println(result);
	}
}

Output:

[98, 99, 85, 88]

Usage of joining()


  • It returns a Collector that concatenates the input elements into a String, in encounter order.
  • It returns a Collector that concatenates the input elements, separated by the specified delimiter, in an encounter order
  • It returns a Collector that concatenates the input elements, separated by the specified delimiter, with the specified prefix and suffix, in encounter order




import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class UserInput {
	
	public static void main(String[] args) {
		
		List laptops = List.of("HP", "Acer", "Dell", "Macbook Air", "Lenovo");
		
		String joinStrings = laptops.stream()
					    .collect(Collectors.joining());
		System.out.println(joinStrings);
		
		String joinWithSpace = laptops.stream()
					      .collect(Collectors.joining(" "));
		
		System.out.println(joinWithSpace);
		
	}
}

Output:

HPAcerDellMacbook AirLenovo
HP Acer Dell Macbook Air Lenovo

Usage of counting()


It returns the number of value in given stream

import java.util.List;
import java.util.stream.Collectors;

public class UserInput {
	
	public static void main(String[] args) {
		
		List laptops = List.of("HP", "Acer", "Dell", "Macbook Air", "Lenovo");
		
		Long result = laptops.stream()
				     .collect(Collectors.counting());
		
		System.out.println(result);
		
	}
}

Output:

5

Usage of maxBy() and minBy()


maxBy() and minBy() collectors return the biggest or the smallest element of Stream according to a provided Comparator instance

import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class UserInput {
	
	public static void main(String[] args) {
		
		List numbers = List.of(98, 34, 66, 28, 56, 90, 33);
		
		Optional max = numbers.stream()
						.collect(Collectors.maxBy(Comparator.naturalOrder()));
		
		System.out.println(max);
		
		Optional min = numbers.stream()
				               .collect(Collectors.minBy(Comparator.naturalOrder()));
		
		System.out.println(min);
		
	}
}

Output:

Optional[98]
Optional[28]

Usage of toList()


Collectors.toList() method is used to convert stram into List

import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class UserInput {
	
	public static void main(String[] args) {
		
		List numbers = List.of(98, 34, 66, 28, 56, 90, 33);
		
		numbers.stream()
				.collect(Collectors.toList())
				.forEach(System.out::println);
		
		
	}
}

Output:

98
34
66
28
56
90
33

Usage of toSet()


Collectors.toSet() method is used to convert into Set

import java.util.List;
import java.util.stream.Collectors;

public class UserInput {
	
	public static void main(String[] args) {
		
		List numbers = List.of(98, 34, 66, 28, 56, 34, 98);
		
		numbers.stream()
				.collect(Collectors.toSet())
				.forEach(System.out::println);
	}
}

Output:

98
34
66
56
28




About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *