常用的Lambda表達式


   Java 8 引入Lambda表達式,對於Java開發人員來說是一大福利,簡化了代碼,提高了開發效率。

  本文主要講解日常開發中使用頻率比較高的幾類Lambda表達式。

集合

  Lambda表達式的引入,大大的方便了我們的集合操作,使得Map,list之間的轉換變得簡單了。

List<T> ---> map<S,List<T>>

Map<String, List<Entity>> demoMap = demoList.stream().collect(Collectors.groupingBy(Entity::getkey));

List<T> ---> map<S,T>

/**
* toMap 如果集合對象有重復的key,會報Duplicate key...錯, * 可以用 (k1,k2)->k1來設置,如果有重復的key,則保留key1,舍棄key2 */ Map<String,Entity> map = stats.stream().collect(Collectors.toMap(Entity::getKey,c -> c,(k1,k2)->k1))); Map<String,String> map = stats.stream().collect(Collectors.toMap(Entity::getKey,Entity::getStringValue));

map<S,List<T>> ---->List<T>

List<Entity> demoList = dataMap.entrySet().stream().flatMap(map -> map.getValue().stream()).collect(Collectors.toList());

線程

普通開啟異步線程

new Thread(() -> System.out.println("Thread Starting......")).start();

線程池開啟異步線程(不接收返回參數)

public static ExecutorService executor = Executors.newFixedThreadPool(10);
executor.submit(() -> aiCollectionFacade.initAiCollection(dto));

線程池開啟異步線程(接收返回參數)

public static ExecutorService executor = Executors.newFixedThreadPool(10);
Future<?> result = executor.submit(() -> sum(a, b));
System.out.println(result.get());

Stream類

創建Stream的方法

   使用range方法給定一個范圍來創建一個基本類型的流。 

IntStream intStream = IntStream.range(1,100); 

  直接給值來創建流 

Stream stream = Stream.of(“hanjt”,”is”,”the”,”most”,”dashing”); 

  由數組創建流 

IntStream stream2 = Arrays.stream(numbers2); 

  由文件生成流 

try { 
    Stream lines = Files.lines(Paths.get(“data.txt”),Charset.defaultCharset()); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

  由函數生成流 

迭代:Stream.iterate(0, n -> n + 2).limit(10) .forEach(System.out::println); 
生成:Stream.generate(Math::random).limit(5) .forEach(System.out::println);

Stream相關的Lambda表達式

屬性過濾

List vegetarian = menu.stream().filter(Dish::isVegetarian) .collect(Collectors.toList()); 

條件過濾

List numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4); 
numbers.stream().filter(i -> i % 2 ==0).distinct().forEach(System.out::println); 

截斷

List dishes = menu.stream().filter(d -> d.getCalories() >300).limit(3) .collect(toList()); 

跳過元素 

List dishes = menu.stream().filter(d -> d.getCalories() >300).skip(2) .collect(toList()); 

映射 

List dishNames =menu.stream().map(Dish::getName).collect(toList());
List words = Arrays.asList(“Java8”, “Lambdas”, “In”, “Action”); 
List wordLengths = words.stream().map(String::length) .collect(toList()); 

展開

List uniqueCharacters = words.stream().map(w -> w.split(“”)) .flatMap(Arrays::stream).distinct().collect(Collectors.toList());

任意匹配 

if(menu.stream().anyMatch(Dish::isVegetarian)){ 
  System.out.println(“The menu is (somewhat) vegetarian friendly!!”); 
} 

全部匹配 

boolean isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000); 

全部不匹配 

boolean isHealthy = menu.stream().noneMatch(d -> d.getCalories() >= 1000); 

獲取任意元素 

Optional dish =menu.stream() .filter(Dish::isVegetarian).findAny(); 歸約 

計算

int sum2 = numbers.stream().reduce(0, (a,b) -> a + b); 
int sum3 = menu.stream().map(Dish::getColories).reduce(0, Integer::sum); 
//如果已知數據類型,可用下面方法。
//但僅支持int doule.long
int sum4 = people.stream().mapToInt(p -> p.getAge()).sum();

求最值 

Optional max = numbers.stream().reduce(Integer::max); 
Optional min = numbers.stream().reduce(Integer::min);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM