Java 8引入了Stream API,Stream這個概念是Java8新引入的函數式編程的一部分。Stream超級方便,極大簡化了對集合的操作,它允許你以一種聲明的方式處理數據的集合。Stream API的所有集合操作都是以類似流水線的方式完成的。它允許你在單個表達式中對數據集合執行複雜的查詢和轉換。Stream API在性能方面也有一定優勢,但是必須合理地使用。在Stream API中,findfirst函數是一個非常有用的函數。
一、findfirst函數是做什麼的?
findfirst函數是Stream中的一個操作函數,它會返回集合中的第一個元素,如果集合為空,它會返回一個空的Optional(Java8中引入的一個新類型,代表一個值存在或不存在),這個函數只是在調用的時候才會去執行,並且它只會返回一個元素。
這裡有一個簡單的例子來說明一下findfirst函數的作用:
List<Integer> numList = Arrays.asList(2,4,6,8,10,12,14,16,18,20); Optional<Integer> firstEven = numList.stream() .filter(num -> num % 2 == 0) .findFirst(); if(firstEven.isPresent()){ System.out.println("The first even number we found is " + firstEven.get()); } else { System.out.println("No even number found in the list"); }
我們首先創建了一個包含10個偶數的List,然後使用Stream對它進行過濾操作,留下所有的偶數,最後使用findFirst函數得到第一個偶數,如果Stream為空的話,它會返回一個空的Optional對象。
二、findfirst函數的應用場景是什麼?
findFirst函數可以用於判斷集合中是否有符合指定條件的元素,只需要判斷它返回的Optional對象是否為空即可。常見的應用場景包括:通過findFirst函數查找集合中的第一個元素、查找符合條件的任意一個元素、根據某個關鍵詞查找元素等。
一個非常實用的應用場景是實現緩存擊穿。緩存穿透是指查詢緩存和數據庫中都不存在的數據,這時候可以用findFirst函數去數據庫中查找第一條記錄,數據庫中有緩存中沒有,這時候將數據放入緩存中,下次遇到同樣的查詢就直接從緩存中獲取。
三、findfirst函數的代碼示例
示例1:通過findFirst函數查找集合中的第一個元素
List<String> strList = Arrays.asList("apple", "banana", "grape", "orange", "pear"); Optional<String> firstElement = strList.stream().findFirst(); if(firstElement.isPresent()){ System.out.println("The first element in the list is " + firstElement.get()); } else { System.out.println("The list is empty"); }
示例2:查找集合中任意一個符合條件的元素
List<Integer> numList = Arrays.asList(10,8,12,6,15,9,20,18,5,3); Optional<Integer> firstMatch = numList.stream() .filter(num -> num % 5 == 0) .findFirst(); if(firstMatch.isPresent()){ System.out.println("The first number we found that is divisible by 5 is " + firstMatch.get()); } else { System.out.println("No number found in the list that is divisible by 5"); }
示例3:通過findFirst函數查找Map中的元素
Map<String, String> map = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); put("key3", "value3"); }}; String key = "key3"; Optional<String> value = map.entrySet().stream() .filter(entry -> key.equals(entry.getKey())) .map(Map.Entry::getValue) .findFirst(); if(value.isPresent()){ System.out.println("The value of key " + key + " is " + value.get()); } else { System.out.println("The key " + key + " does not exist in the map"); }
示例4:實現緩存擊穿
String key = "cache_key"; Cache cache = getCache(); Object value = cache.get(key); if(value == null){ Optional<Object> data = getDataFromDB(); if(data.isPresent()){ value = data.get(); cache.put(key, value); } else { cache.put(key, DEFAULT_VALUE); value = DEFAULT_VALUE; } } return value;
四、總結
findfirst函數在Stream API中是一個非常有用的函數,可以快速地查詢集合中符合條件的元素,適用於各種場合。但是必須合理地使用,否則會對程序的性能帶來影響。建議在編寫代碼的時候,掌握好Stream API的相關知識,以便更加高效地編寫Java程序。
原創文章,作者:RVUGT,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/332161.html