Fork me on GitHub

常用的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);

 

作者:JackpotHan
欢迎任何形式的转载,但请务必注明出处。
限于本人水平,如果文章和代码有表述不当之处,还请不吝赐教。

posted @   JackpotHan  阅读(2548)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示