记录一下,laravel collection和 java stream 的用法和区别
文章目錄
- Stream 簡介
- 定義
- 三個步驟
- 特性
- 性能?
- 一段代碼的思考
- Laravel collection 常用方法 -> Java
- all()
- avg() average() max() min()
- contains()
- diff()
- filter() intersect() where() whereIn()
- first()
- groupBy()
- isEmpty() isNotEmpty()
- keyBy()
- map()
- pluck() transform()
- unique()
- 參考資料:
Stream 簡介
定義
Stream 是 Java8 中處理集合的關鍵抽象概念,它可以指定你希望對集合進行的操作,可以執行非常復雜的查找、過濾和映射數據等操作。使用 Stream API 對集合數據進行操作,就類似于使用 SQL 執行的數據庫查詢。也可以使用 Stream API 來并行執行操作。簡而言之,Stream API提供了一種高效且易于使用的處理數據的方式。
三個步驟
創建->中間操作->中止操作
中間操作
- 篩選與切片(比如:filter-篩選,limit-切片)
- 映射(比如:map)
- 排序(比如:sorted)
中止操作
- 查找與匹配(比如:findFirst)
- 歸約 (比如:reduce)
- 收集 (比如collect(Collector c))
特性
- 無存儲。stream不是一種數據結構,它只是某種數據源的一個視圖,數據源可以是一個數組,Java容器或I/O channel等。
- 為函數式編程而生。對stream的任何修改都不會修改背后的數據源,比如對stream執行過濾操作并不會刪除被過濾的元素,而是會產生一個不包含被過濾元素的新stream。
- 惰式執行。stream上的操作并不會立即執行,只有等到用戶真正需要結果的時候才會執行。
- 可消費性。stream只能被“消費”一次,一旦遍歷過就會失效,就像容器的迭代器那樣,想要再次遍歷必須重新生成。
性能?
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-gFPQeozi-1596436433091)(http://doc.oss.yunsom.cn/storage/2020/07-30/ZHr1sJu7qnLxeLozS06iA2xs1yi6no9WgZypHXle.jpeg “size:800,1000”)]
總結如下:
- 對于簡單操作,比如最簡單的遍歷,Stream串行API性能明顯差于顯示迭代,但并行的Stream API能夠發揮多核特性。
- 對于復雜操作,Stream串行API性能可以和手動實現的效果匹敵,在并行執行時Stream API效果遠超手動實現。
所以,如果出于性能考慮1、對于簡單操作推薦使用外部迭代手動實現 2、對于復雜操作,推薦使用Stream API 3、在多核情況下,推薦使用并行Stream API來發揮多核優勢, 4、單核情況下不建議使用并行Stream API。 - 如果出于代碼簡潔性考慮,使用Stream API能夠寫出更短的代碼。即使是從性能方面說,盡可能的使用Stream API也另外一個優勢,那就是只要Java Stream類庫做了升級優化,代碼不用做任何修改就能享受到升級帶來的好處。<
一段代碼的思考
Stream.of(1,2,3,4,5,6,7,8).sequential().filter(i -> {System.out.println("過濾掉小于2的數據,數據項" + i);return i > 2;}).distinct().map(i -> {System.out.println("給數據加五" + i);return i + 5;}).collect(Collectors.toList());Stream.of(1,2,3,4,5,6,7,8).parallel().filter(i -> {System.out.println("過濾掉小于2的數據,數據項" + i);return i > 2;}).distinct().map(i -> {System.out.println("給數據加五" + i);return i + 5;}).collect(Collectors.toList());Laravel collection 常用方法 -> Java
all()
all 方法返回該集合表示的底層數組
collect([1,3,5])->all(); Arrays.asList(1,3,5).stream().collect(Collectors.toList());avg() average() max() min()
avg 方法返回給定的 平均值
collect([1,3,5])->avg(); Arrays.asList(1,3,5).stream().mapToInt(Integer::intValue).average()contains()
contains 方法判斷集合是否包含給定的項目
collect([1,3,5])->contains(1); // true Arrays.asList(1,3,5).contains(1)diff()
diff 方法將集合與其它集合或純 PHP 數組進行值的比較,然后返回原集合中存在而給定集合中不存在的值
$collection = collect([1, 2, 3, 4, 5]);$diff = $collection->diff([2, 4, 6, 8]);$diff->all(); // [1, 3, 5] List<Integer> collection = Arrays.asList(1, 2, 3, 4, 5);// ArraysList 才支持 removeAllList<Integer> diff = new ArrayList<>(collection);diff.removeAll(Arrays.asList(2, 4, 6, 8));filter() intersect() where() whereIn()
filter 方法使用給定的回調函數過濾集合的內容,只留下那些通過給定真實測試的內容
$collection = collect([1, 2, 3, 4]);$filtered = $collection->filter(function ($value, $key) {return $value > 2; });$filtered->all();// [3, 4] List<Integer> collection = Arrays.asList(1, 2, 3, 4);List<Integer> filtered = collection.stream().filter(p -> p > 2).collect(Collectors.toList());first()
first 方法返回集合中通過給定真實測試的第一個元素
collect([1, 2, 3, 4])->first(function ($value, $key) {return $value > 2; });// 3 Optional<Integer> first = Arrays.asList(1, 2, 3, 4).stream().filter(p -> p > 2).findFirst();if (first.isPresent()) {System.out.println(first.get());}groupBy()
groupBy 方法根據給定的鍵對集合內的項目進行分組
$collection = collect([['account_id' => 'account-x10', 'product' => 'Chair'],['account_id' => 'account-x10', 'product' => 'Bookcase'],['account_id' => 'account-x11', 'product' => 'Desk'], ]);$grouped = $collection->groupBy('account_id');$grouped->toArray();/*['account-x10' => [['account_id' => 'account-x10', 'product' => 'Chair'],['account_id' => 'account-x10', 'product' => 'Bookcase'],],'account-x11' => [['account_id' => 'account-x11', 'product' => 'Desk'],],] */ @Data@AllArgsConstructorclass Product {private String accountId;private String product;}List<Product> collection = Arrays.asList(new Product("account-x10", "Chair"),new Product("account-x10", "Bookcase"),new Product("account-x11", "Desc"));Map<String, List<Product>> grouped = collection.stream().collect(Collectors.groupingBy(Product::getAccountId));isEmpty() isNotEmpty()
如果集合是空的,isEmpty 方法返回 true,否則返回 false
collect([])->isEmpty();// true CollectionUtils.isEmpty(null);keyBy()
keyBy 方法以給定的鍵作為集合的鍵。如果多個項目具有相同的鍵, 則只有最后一個項目回顯示在新集合中
$collection = collect([['product_id' => 'prod-100', 'name' => 'Desk'],['product_id' => 'prod-200', 'name' => 'Chair'], ]);$keyed = $collection->keyBy('product_id');$keyed->all();/*['prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],] */ @Data@AllArgsConstructorclass Product {private String accountId;private String product;}List<Product> collection = Arrays.asList(new Product("account-x10", "Chair"),new Product("account-x10", "Bookcase"),new Product("account-x11", "Desc"));Map<String, Product> keyed = collection.stream().collect(Collectors.toMap(Product::getAccountId, p->p, (exist, replace) -> (replace)));map()
map 方法遍歷集合并將每一個值傳入給定的回調方法。該回調可以任意修改項目并返回,從而形成新的被修改過項目的集合:
$collection = collect([1, 2, 3, 4, 5]);$multiplied = $collection->map(function ($item, $key) {return $item * 2; });$multiplied->all();// [2, 4, 6, 8, 10] List<Integer> collection = Arrays.asList(1, 2, 3, 4, 5);List<Integer> multiplied = collection.stream().map(p -> p * 2).collect(Collectors.toList());pluck() transform()
pluck 方法可以獲取集合中給定鍵對應的所有值:
$collection = collect([['product_id' => 'prod-100', 'name' => 'Desk'],['product_id' => 'prod-200', 'name' => 'Chair'], ]);$plucked = $collection->pluck('name');$plucked->all();// ['Desk', 'Chair'] @Data@AllArgsConstructorclass Product {private String accountId;private String product;}List<Product> collection = Arrays.asList(new Product("account-x10", "Chair"),new Product("account-x10", "Bookcase"),new Product("account-x11", "Desc"));List<String> plucked = collection.stream().map(Product::getAccountId).collect(Collectors.toList());unique()
unique 方法返回集合中所有唯一的項目。返回的集合保留著原數組的鍵,所以在這個例子中,我們使用 values 方法來把鍵重置為連續編號的索引:
$collection = collect([1, 1, 2, 2, 3, 4, 2]);$unique = $collection->unique();$unique->values()->all();// [1, 2, 3, 4] List<Integer> unique = Arrays.asList(1, 2,2, 3, 4, 5) .stream().distinct().collect(Collectors.toList());參考資料:
- https://blog.csdn.net/weixin_37948888/article/details/96995312
- https://learnku.com/docs/laravel/5.7/collections/2279
- https://zhuanlan.zhihu.com/p/92419004
- http://doc.oss.yunsom.cn/project/41?p=927
總結
以上是生活随笔為你收集整理的记录一下,laravel collection和 java stream 的用法和区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Photoshop制作漂亮的圣诞树
- 下一篇: 为什么大部分牛人会选择通达信交易接口?