📜  如何在Java 8 中打印 Stream 的元素

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

如何在Java 8 中打印 Stream 的元素

在Java 8 中引入的 Stream API 用于处理对象的集合。流是支持各种方法的对象序列,这些方法可以流水线化以产生所需的结果。
Java流的特点是——

  • 流不是数据结构,而是从集合、数组或 I/O 通道获取输入。
  • 流不会更改原始数据结构,它们仅根据流水线方法提供结果。
  • 每个中间操作都被延迟执行并返回一个流作为结果,因此可以对各种中间操作进行流水线化。终端操作标记流的结束并返回结果。

有 3 种方法可以在Java中打印 Stream 的元素:

  1. forEach()
  2. println() 和 collect()
  3. 窥视()

以下是详细打印 Stream 的三种方式:

  1. Stream forEach(Consumer action) :此方法对流的每个元素执行一个操作。 Stream forEach(Consumer action) 是一个终端操作,即它可以遍历流以产生结果或副作用。

    句法 :

    void forEach(Consumer action)
    
    Where, Consumer is a functional interface
    and T is the type of stream elements.
    

    下面是如何使用 forEach() 方法打印 Stream 的元素:

    方案一:

    // Java code to print the elements of Stream
      
    import java.util.stream.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Get the stream
            Stream stream = Stream.of("Geeks", "For",
                                              "Geeks", "A",
                                              "Computer", "Portal");
      
            // Print the stream
            stream.forEach(s -> System.out.println(s));
        }
    }
    
    输出:
    Geeks
    For
    Geeks
    A
    Computer
    Portal
    

    程序 2:使用简写 lambda 表达式

    // Java code to print the elements of Stream
      
    import java.util.stream.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Get the stream
            Stream stream = Stream.of("Geeks", "For",
                                              "Geeks", "A",
                                              "Computer", "Portal");
      
            // Print the stream
            stream.forEach(System.out::println);
        }
    }
    
    输出:
    Geeks
    For
    Geeks
    A
    Computer
    Portal
    

    程序 3:这种方法消耗流并使其不可用以供将来使用。因此,由于流已被消耗,以下代码将引发错误。

    // Java code to print the elements of Stream
      
    import java.util.stream.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Get the stream
            Stream stream = Stream.of("Geeks", "For",
                                              "Geeks", "A",
                                              "Computer", "Portal");
      
            // Print the stream
            stream.forEach(s -> System.out.println(s));
      
            // Since the stream has been already consumed
            // this will throw exception
            try {
      
                // Print the stream
                stream.forEach(s -> System.out.println(s));
            }
      
            catch (Exception e) {
      
                System.out.println("\nException: " + e);
            }
        }
    }
    
    输出:
    Geeks
    For
    Geeks
    A
    Computer
    Portal
    
    Exception: java.lang.IllegalStateException: 
    stream has already been operated upon or closed
    
  2. 将 println() 与 collect() 一起使用:此方法将流的元素收集为收集器实例,例如 List。因此,使用 println() 方法可以轻松完成 List 的打印。

    句法:

    System.out.println(stream.collect(Collectors.toList()));
    

    方案一:

    // Java code to print the elements of Stream
      
    import java.util.stream.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Get the stream
            Stream stream = Stream.of("Geeks", "For",
                                              "Geeks", "A",
                                              "Computer", "Portal");
      
            // Print the stream
            System.out.println(stream.collect(Collectors.toList()));
        }
    }
    
    输出:
    [Geeks, For, Geeks, A, Computer, Portal]
    

    程序 2:这种方法还消耗流并使其不可用以供将来使用。因此,由于流已被消耗,以下代码将引发错误。

    // Java code to print the elements of Stream
      
    import java.util.stream.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Get the stream
            Stream stream = Stream.of("Geeks", "For",
                                              "Geeks", "A",
                                              "Computer", "Portal");
      
            // Print the stream
            System.out.println(stream.collect(Collectors.toList()));
      
            // Since the stream has been already consumed
            // this will throw exception
            try {
      
                // Print the stream
                System.out.println(stream.collect(Collectors.toList()));
            }
      
            catch (Exception e) {
      
                System.out.println("\nException: " + e);
            }
        }
    }
    
    输出:
    [Geeks, For, Geeks, A, Computer, Portal]
    
    Exception: java.lang.IllegalStateException: 
    stream has already been operated upon or closed
    
  3. Stream peek(Consumer action) :此方法返回由该流的元素组成的流,在从结果流中消耗元素时,另外对每个元素执行提供的操作。这是一个中间操作,即它创建一个新流,当遍历该流时,它包含与给定谓词匹配的初始流的元素。

    句法 :

    Stream 
        peek(Consumer action)
    
    Where, Stream is an interface and T is the type of 
    stream elements. action is a non-interfering action
    to perform on the elements as they are consumed 
    from the stream and the function returns the new stream.
    

    方案一:

    // Java code to print the elements of Stream
      
    import java.util.stream.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Get the stream
            Stream stream = Stream.of("Geeks", "For",
                                              "Geeks", "A",
                                              "Computer", "Portal");
      
            // Print the stream using peek()
            // by providing a terminal operation count()
            stream.peek(s -> System.out.println(s)).count();
        }
    }
    
    输出:
    Geeks
    For
    Geeks
    A
    Computer
    Portal
    

    方案 2:这种方法不消耗流。因此下面的代码不会抛出任何错误。

    // Java code to print the elements of Stream
      
    import java.util.stream.*;
      
    class GFG {
        public static void main(String[] args)
        {
      
            // Get the stream
            Stream stream = Stream.of("Geeks", "For",
                                              "GeeksForGeeks", "A",
                                              "Computer", "Portal");
      
            // Since the stream is not being consumed
            // this will not throw any exception
      
            // Print the stream
            stream.filter(s -> s.startsWith("G"))
                .peek(s -> System.out.println("Filtered value: " + s))
                .map(String::toUpperCase)
                .peek(s -> System.out.println("Uppercase value :" + s))
                .count();
        }
    }
    
    输出:
    Filtered value: Geeks
    Uppercase value :GEEKS
    Filtered value: GeeksForGeeks
    Uppercase value :GEEKSFORGEEKS