當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stream builder()用法及代碼示例


流builder()返回流的構建器。

用法:

static <T> Stream.Builder<T> builder()

where, T is the type of elements.

返回值:流構建器。


示例1:

// Java code for Stream builder() 
import java.util.*; 
import java.util.stream.Stream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Using Stream builder() 
        Stream.Builder<String> builder = Stream.builder(); 
  
        // Adding elements in the stream of Strings 
        Stream<String> stream = builder.add("Geeks").build(); 
  
        // Displaying the elements in the stream 
        stream.forEach(System.out::println); 
    } 
}

輸出:

Geeks

示例2:

// Java code for Stream builder() 
import java.util.*; 
import java.util.stream.Stream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Using Stream builder() 
        Stream.Builder<String> builder = Stream.builder(); 
  
        // Adding elements in the stream of Strings 
        Stream<String> stream = builder.add("Geeks") 
                                    .add("for") 
                                    .add("Geeks") 
                                    .add("GeeksQuiz") 
                                    .build(); 
  
        // Displaying the elements in the stream 
        stream.forEach(System.out::println); 
    } 
}

輸出:

Geeks
for
Geeks
GeeksQuiz

示例3:

// Java code for Stream builder() 
import java.util.*; 
import java.util.stream.Stream; 
import java.util.stream.Collectors; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // Using Stream builder() 
        Stream.Builder<String> builder = Stream.builder(); 
  
        // Adding elements in the stream of Strings 
        Stream<String> stream = builder.add("GEEKS") 
                                    .add("for") 
                                    .add("Geeks") 
                                    .add("GeEKSQuiz") 
                                    .build(); 
  
        // Converting elements to Lower Case 
        // and storing them in List list 
        List<String> list = stream.map(String::toLowerCase) 
                                .collect(Collectors.toList()); 
  
        // Displaying the elements in list 
        System.out.println(list); 
    } 
}

輸出:

[geeks, for, geeks, geeksquiz]


相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Stream builder() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。