Java 8 中 Stream 和 Collection 的區別


Java 集合框架用於儲存和操作一組資料。它是一種記憶體中的資料結構,集合中的每個元素都必須在新增到集合之前計算出來。

Stream API 僅用於處理一組資料。它不會修改實際的集合,它們只根據管道方法提供結果。

序號關鍵集合
1
基本
它用於儲存和操作一組資料
Stream API 僅用於處理一組資料
2

此 API 的所有類和介面都在 Java.util 包中
此 API 的所有類和介面都在 java.util.stream 包中
3
急切/惰性
集合中的所有元素都在開始時計算。
在流中,中間操作是惰性的。
4.
資料修改
在集合中,我們可以刪除或新增元素。
我們無法修改流。
5
外部/內部迭代器
集合在集合上執行迭代。
流在內部執行迭代。

集合示例

public class CollectiosExample {
   public static void main(String[] args) {

      List<String> laptopList = new ArrayList<>();
      laptopList.add("HCL");
      laptopList.add("Apple");
      laptopList.add("Dell");
      Comparator<String> com = (String o1, String o2)->o1.compareTo(o2);

      Collections.sort(laptopList,com);

      for (String name : laptopList) {
         System.out.println(name);
      }
   }
}

流示例

public class StreamsExample {
   public static void main(String[] args) {

      List<String> laptopList = new ArrayList<>();
      laptopList.add("HCL");
      laptopList.add("Apple");
      laptopList.add("Dell");
      laptopList.stream().sorted().forEach(System.out::println);
   }
}

更新於: 2020-09-09

5K+ 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告