个性化阅读
专注于IT技术分析

如何在Java 8中从Stream获取ArrayList?

给定一个Stream, 任务是将该流转换为Java 8中的ArrayList。

例子:

Input: Stream: [1, 2, 3, 4, 5]
Output: ArrayList: [1, 2, 3, 4, 5]

Input: Stream: ['G', 'e', 'e', 'k', 's']
Output: ArrayList: ['G', 'e', 'e', 'k', 's']

使用Collectors.toList()方法:

  1. 获取要转换的流。
  2. 使用collect()和Collectors.toList()方法将流收集为List。
  3. 将此列表转换为ArrayList
  4. 返回/打印ArrayList

下面是上述方法的实现:

程序:

//Java program to convert Stream to ArrayList
//using Collectors.toList() method
  
import java.util.*;
import java.util.stream.*;
  
public class GFG {
  
     //Function to get ArrayList from Stream
     public static <T> ArrayList<T>
     getArrayListFromStream(Stream<T> stream)
     {
  
         //Convert the Stream to List
         List<T>
             list = stream.collect(Collectors.toList());
  
         //Create an ArrayList of the List
         ArrayList<T>
             arrayList = new ArrayList<T>(list);
  
         //Return the ArrayList
         return arrayList;
     }
  
     //Driver code
     public static void main(String args[])
     {
  
         Stream<Integer>
             stream = Stream.of( 1 , 2 , 3 , 4 , 5 );
  
         //Convert Stream to ArrayList in Java
         ArrayList<Integer>
             arrayList = getArrayListFromStream(stream);
  
         //Print the arraylist
         System.out.println( "ArrayList: " + arrayList);
     }
}

输出如下:

ArrayList: [1, 2, 3, 4, 5]

使用Collectors.toCollection()方法:

方法:

  1. 获取要转换的流。
  2. 使用collect()和Collectors.toCollection()方法将流收集为ArrayList。
  3. 返回/打印ArrayList

下面是上述方法的实现:

程序:

//Java program to convert Stream to ArrayList
//using Collectors.toList() method
  
import java.util.*;
import java.util.stream.*;
  
public class GFG {
  
     //Function to get ArrayList from Stream
     public static <T> ArrayList<T>
     getArrayListFromStream(Stream<T> stream)
     {
  
         //Convert the Stream to ArrayList
         ArrayList<T>
             arrayList = stream
                             .collect(Collectors
                             .toCollection(ArrayList:: new ));
  
         //Return the ArrayList
         return arrayList;
     }
  
     //Driver code
     public static void main(String args[])
     {
  
         Stream<Integer>
             stream = Stream.of( 1 , 2 , 3 , 4 , 5 );
  
         //Convert Stream to ArrayList in Java
         ArrayList<Integer>
             arrayList = getArrayListFromStream(stream);
  
         //Print the arraylist
         System.out.println( "ArrayList: "
                            + arrayList);
     }
}

输出如下:

ArrayList: [1, 2, 3, 4, 5]

赞(0)
未经允许不得转载:srcmini » 如何在Java 8中从Stream获取ArrayList?

评论 抢沙发

评论前必须登录!