[Java] Stream Intro example

public class Code {
  public static void main(String[] args) {
    Arrays.asList("red", "green", "blue")
          .stream()
          .sorted()
          .findFirst()
          .ifPresent(System.out::println) // blue
      
    Stream.of("apple", "pear", "banana", "cherry", "apricot")
          .filter(fruit -> {
          return fruit.startsWith("a");
        })
                // if forEach is removed, nothing will print
       // the foreach makes it a terminal event
          .forEach(fruit -> System.out.println("Starts with A: " + fruit));
      
    // using a stream and map operation to create alist of words in caps
    List<String> collected = Stream.of("Java", "Rocks")
          .map(string -> string.toUpperCase())
          .collect(toList());
    System.out.println(collected.toString());
  }
}

 

posted @ 2020-12-30 03:43  Zhentiw  阅读(64)  评论(0编辑  收藏  举报