📜  Java中的 Stream builder() 和示例

📅  最后修改于: 2022-05-13 01:55:13.630000             🧑  作者: Mango

Java中的 Stream builder() 和示例

Stream builder()返回 Stream 的构建器。

句法 :

static  Stream.Builder 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 builder = Stream.builder();
  
        // Adding elements in the stream of Strings
        Stream 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 builder = Stream.builder();
  
        // Adding elements in the stream of Strings
        Stream 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 builder = Stream.builder();
  
        // Adding elements in the stream of Strings
        Stream stream = builder.add("GEEKS")
                                    .add("for")
                                    .add("Geeks")
                                    .add("GeEKSQuiz")
                                    .build();
  
        // Converting elements to Lower Case
        // and storing them in List list
        List list = stream.map(String::toLowerCase)
                                .collect(Collectors.toList());
  
        // Displaying the elements in list
        System.out.println(list);
    }
}

输出 :

[geeks, for, geeks, geeksquiz]