Collection()
Java中Collectors类的to方法返回一个Collector,该Collector以遇到的顺序将输入元素累积到一个新的Collection中。语法如下-
static <T,C extends Collection<T>> Collector<T,?,C> toCollection(Supplier<C> collectionFactory)
在这里,T-是输入元素的类型,C是结果集合的类型,Supplier是结果的供应商,Collection工厂是返回适当类型的新的空Collection的Supplier
现在让我们看一个例子-
import java.util.Collection; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<String> stream = Stream.of("25", "10", "15", "20", "25"); Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new)); System.out.println("Collection = "+collection); } }
输出结果
Collection = [10, 15, 20, 25]
让我们看另一个例子-
import java.util.Collection; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream<String> stream = Stream.of("Jack", "Tom", "Brad", "Tim", "Kevin", "Bradley", "Ryan"); Collection<String> collection = stream.collect(Collectors.toCollection(TreeSet::new)); System.out.println("Collection = "+collection); } }
输出结果
Collection = [Brad, Bradley, Jack, Kevin, Ryan, Tim, Tom]