前言
日常开发中,我们很多时候需要用到Java 8
的Lambda
表达式,它允许把函数作为一个方法的参数,让我们的代码更优雅、更简洁。所以整理了一波工作中,我常用的,有哪些Lambda
表达式。看完一定会有帮助的。
1. list转map
工作中,我们经常遇到list
转map
的案例。Collectors.toMap
就可以把一个list
数组转成一个Map
。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class TestLambda { public static void main(String[] args) { List<userinfo> userInfoList = new ArrayList(); userInfoList.add( new UserInfo(1L, "捡田螺的小男孩" , 18 )); userInfoList.add( new UserInfo(2L, "程序员田螺" , 27 )); userInfoList.add( new UserInfo(2L, "捡瓶子的小男孩" , 26 )); /** * list 转 map * 使用Collectors.toMap的时候,如果有可以重复会报错,所以需要加(k1, k2) -> k1 * (k1, k2) -> k1 表示,如果有重复的key,则保留第一个,舍弃第二个 */ Map< long > userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserInfo::getUserId, userInfo -> userInfo, (k1, k2) -> k1)); userInfoMap.values().forEach(a->System.out.println(a.getUserName())); } } </ long ></userinfo> |
运行结果
捡田螺的小男孩
程序员田螺
类似的,还有Collectors.toList()
、Collectors.toSet()
,表示把对应的流转化为list
或者Set
。
2. filter()过滤
从数组集合中,过滤掉不符合条件的元素,留下符合条件的元素。
1 2 3 4 5 6 7 8 9 10 11 12 | List<userinfo> userInfoList = new ArrayList(); userInfoList.add( new UserInfo(1L, "捡田螺的小男孩" , 18 )); userInfoList.add( new UserInfo(2L, "程序员田螺" , 27 )); userInfoList.add( new UserInfo(3L, "捡瓶子的小男孩" , 26 )); /** * filter 过滤,留下超过18岁的用户 */ List<userinfo> userInfoResultList = userInfoList.stream().filter(user -> user.getAge() > 18 ).collect(Collectors.toList()); userInfoResultList.forEach(a -> System.out.println(a.getUserName())); </userinfo></userinfo> |
运行结果
程序员田螺
捡瓶子的小男孩
3. foreach遍历
foreach 遍历list,遍历map,真的很丝滑。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | /** * forEach 遍历集合List列表 */ List<string> userNameList = Arrays.asList( "捡田螺的小男孩" , "程序员田螺" , "捡瓶子的小男孩" ); userNameList.forEach(System.out::println); HashMap<string> hashMap = new HashMap(); hashMap.put( "公众号" , "捡田螺的小男孩" ); hashMap.put( "职业" , "程序员田螺" ); hashMap.put( "昵称" , "捡瓶子的小男孩" ); /** * forEach 遍历集合Map */ hashMap.forEach((k, v) -> System.out.println(k + ":t" + v)); </string></string> |
运行结果
捡田螺的小男孩
程序员田螺
捡瓶子的小男孩
职业: 程序员田螺
公众号: 捡田螺的小男孩
昵称: 捡瓶子的小男孩
4. groupingBy分组
提到分组,相信大家都会想起SQL
的group by
。我们经常需要一个List做分组操作。比如,按城市分组用户。在Java8之前,是这么实现的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | List<userinfo> originUserInfoList = new ArrayList(); originUserInfoList.add( new UserInfo(1L, "捡田螺的小男孩" , 18 , "深圳" )); originUserInfoList.add( new UserInfo(3L, "捡瓶子的小男孩" , 26 , "湛江" )); originUserInfoList.add( new UserInfo(2L, "程序员田螺" , 27 , "深圳" )); Map<string>> result = new HashMap(); for (UserInfo userInfo : originUserInfoList) { String city = userInfo.getCity(); List<userinfo> userInfos = result.get(city); if (userInfos == null ) { userInfos = new ArrayList(); result.put(city, userInfos); } userInfos.add(userInfo); } </userinfo></string></userinfo> |
而使用Java8的groupingBy
分组器,清爽无比:
1 2 3 | Map<string>> result = originUserInfoList.stream() .collect(Collectors.groupingBy(UserInfo::getCity)); </string> |
5. sorted+Comparator 排序
工作中,排序的需求比较多,使用sorted+Comparator
排序,真的很香。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | List<userinfo> userInfoList = new ArrayList(); userInfoList.add( new UserInfo(1L, "捡田螺的小男孩" , 18 )); userInfoList.add( new UserInfo(3L, "捡瓶子的小男孩" , 26 )); userInfoList.add( new UserInfo(2L, "程序员田螺" , 27 )); /** * sorted + Comparator.comparing 排序列表, */ userInfoList = userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge)).collect(Collectors.toList()); userInfoList.forEach(a -> System.out.println(a.toString())); System.out.println( "开始降序排序" ); /** * 如果想降序排序,则可以使用加reversed() */ userInfoList = userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge).reversed()).collect(Collectors.toList()); userInfoList.forEach(a -> System.out.println(a.toString())); </userinfo> |
运行结果
UserInfo{userId=1, userName=’捡田螺的小男孩’, age=18}
UserInfo{userId=3, userName=’捡瓶子的小男孩’, age=26}
UserInfo{userId=2, userName=’程序员田螺’, age=27}
开始降序排序
UserInfo{userId=2, userName=’程序员田螺’, age=27}
UserInfo{userId=3, userName=’捡瓶子的小男孩’, age=26}
UserInfo{userId=1, userName=’捡田螺的小男孩’, age=18}
6.distinct去重
distinct
可以去除重复的元素:
1 2 3 4 | List<string> list = Arrays.asList( "A" , "B" , "F" , "A" , "C" ); List<string> temp = list.stream().distinct().collect(Collectors.toList()); temp.forEach(System.out::println); </string></string> |
7. findFirst 返回第一个
findFirst
很多业务场景,我们只需要返回集合的第一个元素即可:
1 2 3 | List<string> list = Arrays.asList( "A" , "B" , "F" , "A" , "C" ); list.stream().findFirst().ifPresent(System.out::println); </string> |
8. anyMatch是否至少匹配一个元素
anyMatch
检查流是否包含至少一个满足给定谓词的元素。
1 2 3 4 | Stream<string> stream = Stream.of( "A" , "B" , "C" , "D" ); boolean match = stream.anyMatch(s -> s.contains( "C" )); System.out.println(match); </string> |
输出
true
9. allMatch 匹配所有元素
allMatch
检查流是否所有都满足给定谓词的元素。
1 2 3 4 | Stream<string> stream = Stream.of( "A" , "B" , "C" , "D" ); boolean match = stream.allMatch(s -> s.contains( "C" )); System.out.println(match); </string> |
输出
false
10. map转换
map
方法可以帮我们做元素转换,比如一个元素所有字母转化为大写,又或者把获取一个元素对象的某个属性,demo
如下:
1 2 3 4 5 | List<string> list = Arrays.asList( "jay" , "tianluo" ); //转化为大写 List<string> upperCaselist = list.stream().map(String::toUpperCase).collect(Collectors.toList()); upperCaselist.forEach(System.out::println); </string></string> |
11. Reduce
Reduce可以合并流的元素,并生成一个值
1 2 | int sum = Stream.of( 1 , 2 , 3 , 4 ).reduce( 0 , (a, b) -> a + b); System.out.println(sum); |
12. peek 打印个日志
peek()
方法是一个中间Stream
操作,有时候我们可以使用peek
来打印日志。
1 2 3 4 5 6 | List<string> result = Stream.of( "程序员田螺" , "捡田螺的小男孩" , "捡瓶子的小男孩" ) .filter(a -> a.contains( "田螺" )) .peek(a -> System.out.println( "关注公众号:" + a)).collect(Collectors.toList()); System.out.println(result); </string> |
运行结果
关注公众号:程序员田螺
关注公众号:捡田螺的小男孩
[程序员田螺, 捡田螺的小男孩]
13. Max,Min最大最小
使用lambda流求最大,最小值,非常方便。
1 2 3 4 5 6 7 8 9 10 11 12 | List<userinfo> userInfoList = new ArrayList(); userInfoList.add( new UserInfo(1L, "捡田螺的小男孩" , 18 )); userInfoList.add( new UserInfo(3L, "捡瓶子的小男孩" , 26 )); userInfoList.add( new UserInfo(2L, "程序员田螺" , 27 )); Optional<userinfo> maxAgeUserInfoOpt = userInfoList.stream().max(Comparator.comparing(UserInfo::getAge)); maxAgeUserInfoOpt.ifPresent(userInfo -> System.out.println( "max age user:" + userInfo)); Optional<userinfo> minAgeUserInfoOpt = userInfoList.stream().min(Comparator.comparing(UserInfo::getAge)); minAgeUserInfoOpt.ifPresent(userInfo -> System.out.println( "min age user:" + userInfo)); </userinfo></userinfo></userinfo> |
运行结果
max age user:UserInfo{userId=2, userName=’程序员田螺’, age=27}
min age user:UserInfo{userId=1, userName=’捡田螺的小男孩’, age=18}
14. count统计
一般count()
表示获取流数据元素总数。
1 2 3 4 5 6 7 8 | List<userinfo> userInfoList = new ArrayList(); userInfoList.add( new UserInfo(1L, "捡田螺的小男孩" , 18 )); userInfoList.add( new UserInfo(3L, "捡瓶子的小男孩" , 26 )); userInfoList.add( new UserInfo(2L, "程序员田螺" , 27 )); long count = userInfoList.stream().filter(user -> user.getAge() > 18 ).count(); System.out.println( "大于18岁的用户:" + count); </userinfo> |
输出
大于18岁的用户:2
15. 常用函数式接口
其实lambda离不开函数式接口,我们来看下JDK8常用的几个函数式接口:
-
Function
(转换型): 接受一个输入参数,返回一个结果 -
Consumer
(消费型): 接收一个输入参数,并且无返回操作 -
Predicate
(判断型): 接收一个输入参数,并且返回布尔值结果 -
Supplier
(供给型): 无参数,返回结果
Function
是一个功能转换型的接口,可以把将一种类型的数据转化为另外一种类型的数据
1 2 3 4 5 6 7 8 | private void testFunction() { //获取每个字符串的长度,并且返回 Function<string> function = String::length; Stream<string> stream = Stream.of( "程序员田螺" , "捡田螺的小男孩" , "捡瓶子的小男孩" ); Stream<integer> resultStream = stream.map(function); resultStream.forEach(System.out::println); } </integer></string></string> |
Consumer
是一个消费性接口,通过传入参数,并且无返回的操作
1 2 3 4 5 6 7 | private void testComsumer() { //获取每个字符串的长度,并且返回 Consumer<string> comsumer = System.out::println; Stream<string> stream = Stream.of( "程序员田螺" , "捡田螺的小男孩" , "捡瓶子的小男孩" ); stream.forEach(comsumer); } </string></string> |
Predicate
是一个判断型接口,并且返回布尔值结果.
1 2 3 4 5 6 7 | private void testPredicate() { //获取每个字符串的长度,并且返回 Predicate<integer> predicate = a -> a > 18 ; UserInfo userInfo = new UserInfo(2L, "程序员田螺" , 27 ); System.out.println(predicate.test(userInfo.getAge())); } </integer> |
Supplier
是一个供给型接口,无参数,有返回结果。
1 2 3 4 5 | private void testSupplier() { Supplier<integer> supplier = () -> Integer.valueOf( "666" ); System.out.println(supplier.get()); } </integer> |
这几个函数在日常开发中,也是可以灵活应用的,比如我们DAO操作完数据库,是会有个result的整型结果返回。我们就可以用Supplier
来统一判断是否操作成功。如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | private void saveDb(Supplier<integer> supplier) { if (supplier.get() > 0 ) { System.out.println( "插入数据库成功" ); } else { System.out.println( "插入数据库失败" ); } } @Test public void add() throws Exception { Course course= new Course(); course.setCname( "java" ); course.setUserId(100L); course.setCstatus( "Normal" ); saveDb(() -> courseMapper.insert(course)); }</integer> |
到此这篇关于简单聊聊工作中常用的Java Lambda表达式的文章就介绍到这了,更多相关Java Lambda表达式内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!