赞
踩
a>概念
Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。
使用 Lambda 表达式可以使代码变的更加简洁紧凑。
* 前提是参数接口,且接口中只有一个抽象方法
用lambda表示时 接口中的方法就会省略不写
a>概念
jdk1.8推出的,对某些匿名内部类写法进行简化,
他是函数编程思想的一个重要体现,不在关注是什么对象,更关注对数据进行什么操作。
b>语法格式
(参数列表)->{代码}
java8的Stream使用的是函数编程模式,
可以用来对集合或数组进行链状流式操作。
可以更方便的对集合和数组操作。
filter distinct() map sorted limit skip flatmap
map 只能将一个对象转换为另一个对象
flatmap 可以将一个对象转换为多个对象作为流中的元素
list.stream()
.distinct() //去重复
.sorted() // //排序 实体类必须实现 compared接口,在重写方法中设置排序规则
.sorted((item1,item2)->item1.getAge-item2.getAge) //同上
.limit(5) //设置流的个数超出部分抛弃
.skip(2) //跳过前2条数据
.flatmap(item->item.getBooks.stream()) //getBook是个集合 实际就是返回stream() 类型
.filter(item->item>10 && item<20) //过滤获取item大于10的数据 &&支持多条件过滤
.map(item->item.getName) //转换类型,返回的类型与item.getName类型一致
(且数据流中只有这一列的值)
.sorted()
.foreach(item->System.out.println(item)) ;
foreach //遍历对元素进行操作
count //返回long型 即流中数据的个数
collect //把当前流转换为集合(list set map)
max/min //返回最大值或最小值 只能是int类型 返回 Optional<Integer>
anyMatch //是否有任意匹配的元素 返回boolean
allMatch //是否全部符合条件 返回boolean
noneMatch //是否都不符合条件 返回boolean
findAny //获取流中任意一个元素 返回 Optional<Bean>
findfirst //获取流中的第一个元素 返回 Optional<Bean>
reduce //归并 对流中的元素按照给定的计算方式得到结果
list.stream()
.foreach(item->System.out.println(item)) ;
.count();
.map(item->item.getAge)
.mix((age1,age2)->age1-age2) ;
.map(item->item.getName)
.collect(Collectors.toList()); //将流中所有的name 转换为一个list
.collect(Collectors.toSet()); //将流中所有的name 转换为一个set
.distinct() // map 的key不能重复,必须要去重复
.collect(Collectors.toMap(item->item.getName(),item->item.getBooks())); //将流中所有的name 转换为一个set
.anyMatch(item->item.getAge>30);
.allMatch(item->item.getAge>30);
.noneMatch(item->item.getAge>30);
Optional<Integer> max = list.stream() .
.map(item->item.getAge)
.max((age1,age2)->age1-age2) ;
Optional<Bean> any = list.stream() .
.filter(item->item.getAge>20)
.findAny () ;
any.ifPresent(item->System.out.print(item.getAge))
Optional<Bean> first = list.stream() .
.filter(item->item.getAge>20)
.findFirst () ;
first .ifPresent(item->System.out.print(item.getAge))
类似包装类,将对象封装进这个对象中,用来更好的处理空指针异常问题。
用Optional的静态方法 ofNUllable(Bean) 封装,ifPresent()方法处理是否为空。
ifPresent方法是:如果数据不为空,就执行输出
例: Optional<User> optional = Optional.onNullable(User);
optional.ifPresent(user->System.out.println(user.getName));
优雅的处理控制住方式
参考文档:JAVA8之妙用Optional解决判断Null为空的问题_zjhred的博客-CSDN博客_java8 判断null
- //之前
- if(user!=null){ dosomething(user);}
-
- //现在
- Optional.ofNullable(user).ifPresent(u->{dosomething(u);});
-
- //之前
- public String getCity(User user) throws Exception{
- if(user!=null){
- if(user.getAddress()!=null){
- Address address = user.getAddress();
- if(address.getCity()!=null){
- return address.getCity();
- }
- }
- }
- throw new Excpetion("取值错误");
- }
-
- //现在
- public String getCity(User user) throws Exception{
- return Optional.ofNullable(user)
- .map(u-> u.getAddress())
- .map(a->a.getCity())
- .orElseThrow(()->new Exception("取指错误"));
- }
-
- //之前
- public User getUser(User user) throws Exception{
- if(user!=null){
- String name = user.getName();
- if("zhangsan".equals(name)){
- return user;
- }
- }else{
- user = new User();
- user.setName("zhangsan");
- return user;
- }
- }
-
- //现在
- public User getUser(User user) {
- return Optional.ofNullable(user)
- .filter(u->"zhangsan".equals(u.getName()))
- .orElseGet(()-> {
- User user1 = new User();
- user1.setName("zhangsan");
- return user1;
- });
- }

orElse 和 orElseGet 区别
name.orElse("返回字符串")
name.orElseGet(() -> "返回实现的对象")
有俩种方式实现并行流;
1> stream().parallel()
2> parallelStream()
a>按 BigDecimal 类型 nav 降序排序 存在空指针异常的情况
- // 降序排序 去掉reversed顺序反转
- List<Test> result = list
- .stream()
- .sorted(Comparator.comparing(Test::getNav).reversed())
- .collect(Collectors.toList());
b>. BigDecimal 类型 nav 降序排序,为空的数据 排最后
nullsFirst 为空时排第一 nullsLast 为空时排第最后 可以避免空指针
reversed顺序反转
- List<Test> result = list
- .stream()
- .sorted(Comparator.comparing
- (Test::getNav, Comparator.nullsFirst(BigDecimal::compareTo)).reversed())
- .collect(Collectors.toList());
c>先按 : BigDecimal 类型 nav 升序排序,为空的数据 排最后
再按:BigDecimal 类型 rate 升序排序,为空的数据 排最后
- List<Test> result = list.stream()
- .sorted(Comparator.comparing(Test::getNav,
- Comparator.nullsLast(BigDecimal::compareTo))
- .thenComparing(Test::getRate, Comparator.nullsLast(BigDecimal::compareTo)))
- .collect(Collectors.toList());
d>int 类型 年龄升序排序
- //将list按照年龄从小到大排序
- List<User> collect2 = list
- .stream()
- .sorted((s1, s2) -> s1.getAge() - s2.getAge())
- .collect(Collectors.toList());
-
-
-
- collect2.forEach(x->{
- System.out.print(x.getAge());
- });
e>LIst<Map<String,Object>> 按map中一个属性排序
- //age 为int类型,空的在最后排序
- List<Map<String, Object>> listMap = listMap
- .stream()
- .sorted(Comparator.comparing(a -> (Integer) a.get("age"),
- Comparator.nullsLast(Integer::compareTo)))
- .collect(Collectors.toList());
a> list<BeanA> 转换为 list<BeanB>
- List<StockNoticesVO> result = stockNoticesPOList
- .parallelStream()
- .map(t -> {
- StockNoticesVO stockNoticesVO = new StockNoticesVO();
- BeanUtils.copyProperties(t, stockNoticesVO);
- return stockNoticesVO;
- })
- .collect(Collectors.toList());
b> list 转为 指定的 list或set
- //返回指定的集合 适合 list 和 set
- Set<String> resultSet= list
- .parallelStream()
- .map(t->t.getName)
- .collect(Collectors.toCollection(() -> Sets.newConcurrentHashSet()));
c> 将list<String > 中的小写元素转为大写
- List<String> results = list
- .stream()
- .map(String::toUpperCase)
- .collect(Collectors.toList());
d>list 转map,key为 age,value为name key如果有重复的选第一个
- // 如果(k1, k2) -> k2 则key 重复时 选后面的一个
- list
- .stream()
- collect(Collectors.toMap(t-> t.getAge(), t::getName, (k1, k2) -> k1));
a>对原list<Bean> 属性重新赋值 修改是持久的
- list.stream()
- .forEach(t-> {
- String securityCode = "新securityCode ";
- String stockExchange = "新stockExchange ";
- t.setSecurityCode(securityCode);
- t.setExchange(stockExchange);
- });
a> 获取 一个list<bean>中的属性 存在 与另一个list<Bean2> 中的属性相同的集合
- result = list
- .stream()
- .filter(t-> list2.stream()
- .anyMatch(t2->
- (t.getSecurityCode()).equals(t2.getSecurityCode())
-
- && (t.getExchange()).equals(t2.getExchange()
- )
- )
- )
- .collect(Collectors.toList());
b>多条件过滤
- //可以在filter 中写判断逻辑,必须返回boolean值
- resultList = resultList .stream().filter(f -> {
- if (1!=1) {
- return false;
- }
-
- if (2 != 2) {
- return false;
- }
- return true;
- }).collect(Collectors.toList());
a>BigDecimal 求和
- //求和 并过滤掉空的情况
- BigDecimal sumData = e.stream().map(User::getMoney).filter(StringUtil::isNotEmpty).reduce((x, y) -> x.add(y)).orElse(BigDecimal.ZERO);
a>转map key为tomap 中的第一个参数,value 为 第二个参数
- //返回map中的泛型为 Map<String, t> 对应 t.getName() T 的类型
- Map<String, t> resultMap = list<T>
- .stream()
- .collect(Collectors.toMap(t->t.getName(), t -> t));
- //返回指定的集合 适合 list 和 set
- Set<String> resultSet= list
- .parallelStream()
- .map(t->t.getName)
- .collect(Collectors.toCollection(() -> Sets.newConcurrentHashSet()));
- //返回key是id,value 为自定义的map
- Map<Integer, Map<String, Object>> resultMap= userList
- .stream()
- .collect(Collectors.toMap(User::getId, t -> {
- Map<String, Object> map = Maps.newHashMap();
- map.put("securityId", t.getSecurityId());
- map.put("securityName", t.getSecurityName());
- map.put("windCode",
- return map;
- }, (a, b) -> a)
- );
参考文档:https://www.jb51.net/article/186960.htm#_lab2_2_6
a>maxBy 取出流总元素最大值 针对 int类型
- //取出集合中年龄的最大值
-
- Optional<User> collect1 = list
- .stream()
- .collect(Collectors.maxBy((s1, s2) -> s1.getAge() - s2.getAge()));
b>minBy 取出 流中元素中 长度最好的值 针对String类型
- Optional<String> min = list
- .stream
- .collect(Collectors.minBy(Comparator.comparingInt(String::length)));
c>joining 连接元素 针对String类型
- // 输出 FelordcnTomcatJettyUndertowResin
- list.stream().collect(Collectors.joining());
-
- // 输出 Felordcn,Tomcat,Jetty,Undertow,Resin
- list.stream().collect(Collectors.joining("," ));
-
- // 输出 [Felordcn,Tomcat,Jetty,Undertow,Resin]
- list.stream().collect(Collectors.joining(",", "[", "]"));
d>groupingBy 分组
参考文档:Stream中Collectors.groupingBy toMap mapping操作实例_一笑而过者也的博客-CSDN博客_collectors.mapping和map
- //分组 按某个属性分组 返回格式如下
- Map<String, List<Product>> prodMap= prodList
- .stream()
- .collect(Collectors.groupingBy(Product::getCategory));
-
-
- //{"啤酒":[{"category":"啤酒","id":4,"name":"青岛啤酒","num":3,"price":10},
- {"category":"啤酒","id":5,"name":"百威啤酒","num":10,"price":15}],
- "零食":[{"category":"零食","id":1,"name":"面包","num":1,"price":15.5},
- {"category":"零食","id":2,"name":"饼干","num":2,"price":20},
- {"category":"零食","id":3,"name":"月饼","num":3,"price":30}]}
-
e>Collectors.mapping 重写返回类型Collectors.mapping
参考文档:Java8 Stream Collectors groupingBy 和 mapping 配合使用 - 简书
- //分组后映射map为 sex-set(money)
- Map<String, Set<Double>> collect3 = students
- .stream()
- .collect(Collectors.groupingBy(Student::getSex,
- Collectors.mapping(Student::getMoney, Collectors.toSet())
- )
- );
-
- // 输出为 {女=[40.0, 80.0], 男=[10.0, 20.0]}
a>Collectors.averagingInt Collectors.averagingDouble
List<User>
Double averageAge= userList.stream().collect(Collectors.averagingInt(User::getAge));
List<Integer>
Double averageAge= userList.stream().collect(Collectors.averagingDouble(t->t);
b>mapToDouble
-
- OptionalDouble avg = listUsers.stream().mapToDouble(Users::getAge).average();
- if (avg .isPresent()) { System.out.println(avg .getAsDouble()); }
-
- double avg = listUsers.stream().mapToDouble(Users::getAge).average().getAsDouble();
c>对BigDecimal类型取平均值
参考文档:java8计算list对象BigDecimal属性的最大值、最小值、总和、平均值_X_ABU的博客-CSDN博客_bigdecimal平均值
ROUND_HALF_UP 为四舍五入模式
BigDecimal average = userList.stream().map(User::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(userList.size()), 2, BigDecimal.ROUND_HALF_UP);
d>分组并求和 平均数等
参考文档:利用stream对list集合中的bigdecimal进行分组求和,均值,最大值,最小值_泡^泡的博客-CSDN博客
- //按照性别求分数平均值
- Map<String, BigDecimal> scoreAvg = list.stream()
- .filter(t -> t.getScore() != null)
- .collect(Collectors.groupingBy(Student::getSex, CollectorsUtil.averagingBigDecimal(Student::getScore,2,0)));
-
- System.out.println("----按照性别求分数平均值----");
- scoreAvg.forEach((k,v) -> System.out.println("key: " + k + " , " + "value: " + v));
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。