Java Collectors toList()用法及代码示例

时间:2021-08-21 15:16:22   收藏:0   阅读:15

Collector类的toList()方法是静态(类)方法。

它返回一个Collector接口,该接口将输入数据收集到一个新列表中。

此方法从不保证返回列表的类型,可变性,可序列化性或线程安全性,但可以使用toCollection(Supplier)方法进行更多控制。这是un-orderedCollector。

方法:

public static  Collector<T, ?, R> toList()

返回值:此方法返回一个Collector,该Collector按遇到顺序将所有输入元素收集到一个列表中。

范例1:

import java.util.List; 
import java.util.stream.Collectors; 
import java.util.stream.Stream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // creating a Stream of strings 
        Stream<String> s = Stream.of("Geeks", 
                                     "for", 
                                     "GeeksforGeeks", 
                                     "Geeks Classes"); 
  
        // using Collectors toList() function 
        List<String> myList = s.collect(Collectors.toList()); 
  
        // printing the elements 
        System.out.println(myList); 
    } 
}

输出:

[Geeks, for, GeeksforGeeks, Geeks Classes]

范例2:

import java.util.List; 
import java.util.stream.Collectors; 
import java.util.stream.Stream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
  
        // creating a Stream of strings 
        Stream<String> s = Stream.of("1", "2", "3", "4"); 
  
        // using Collectors toList() function 
        List<String> myList = s.collect(Collectors.toList()); 
  
        // printing the elements 
        System.out.println(myList); 
    } 
}

输出:

[1, 2, 3, 4]

 

 

原文:https://www.cnblogs.com/MR-Mo-7/p/15168947.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!