Collect method of the Stream class

  • Stream.collect() is one of the Java 8’s Stream API‘s terminal methods. It allows us to perform mutable fold operations

Example :

package com.demo;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Example {
	public static void main(String[] args) {
		List<String> resultList1 = Stream.of("Hello","World").collect(Collectors.toList());//Default ArrayList
		List<String> resultList2 = Stream.of("Hello","World").collect(Collectors.toCollection(LinkedList::new));
		Set<String> resultSet = Stream.of("Hello","World").collect(Collectors.toSet());
		Map<String,Integer> resultMap = Stream.of("Hello","World").collect(Collectors.toMap(x->x, y->y.length()));
	}
}

Leave a Comment