一、背景介绍
lambda表达式不算是什么新奇的东西,jdk8诞生也好多年了,但是lambda表达式据我观察,在我多年的开发生涯中,周围同事用的其实不多,具体原因可能还是说不了解,习惯了过去的编程方式等等,其实自己不了解的东西不要抗拒,个人理解都是一个熟悉的过程,熟练以后也没什么大不了。
二、代码示例
package cn.hh.huhy;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author huhy
*/
public class TeamUser {
private String name;
private Integer age;
private String phone;
private String desc;
private double sal;
public TeamUser() {}
public TeamUser(String name, Integer age, String phone, String desc, double sal) {
this.name = name;
this.age = age;
this.phone = phone;
this.desc = desc;
this.sal = sal;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
@Override
public String toString() {
return "TeamUser{" +
"name='" + name + '\'' +
", age=" + age +
", phone='" + phone + '\'' +
", desc='" + desc + '\'' +
", sal=" + sal +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TeamUser teamUser = (TeamUser) o;
return Double.compare(teamUser.sal, sal) == 0 &&
Objects.equals(name, teamUser.name) &&
Objects.equals(age, teamUser.age) &&
Objects.equals(phone, teamUser.phone) &&
Objects.equals(desc, teamUser.desc);
}
@Override
public int hashCode() {
return Objects.hash(name, age, phone, desc, sal);
}
public static final List<TeamUser> createTeamUserList(){
List<TeamUser> users = new ArrayList<>();
users.add(new TeamUser("布隆",40,"13390114667","弗雷尔卓德之心",6000));
users.add(new TeamUser("易大师",36,"13390114668","无极剑圣",8000));
users.add(new TeamUser("德莱厄斯",45,"13310114667","诺克萨斯之手",9000));
users.add(new TeamUser("德莱文",38,"13190114667","诺克萨斯行刑官",10000));
users.add(new TeamUser("赵信",35,"13090114667","德邦总管",9000));
users.add(new TeamUser("嘉文四世",40,"13490114667","德玛西亚皇子",8800));
users.add(new TeamUser("寒冰",30,"13390114667","寒冰射手",6600));
users.add(new TeamUser("大章鱼",40,"13390114667","海兽祭祀",7700));
users.add(new TeamUser("冉闵",40,"11390114667","武悼天王",30000));
users.add(new TeamUser("布隆",40,"13390114667","弗雷尔卓德之心",6000));
users.add(new TeamUser("布隆",40,"13390114667","弗雷尔卓德之心",6000));
return users;
}
}
package cn.hh.huhy;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author huhy
*/
public class SteamTest {
Logger logger = LoggerFactory.getLogger(SteamTest.class);
public void createSteamDemo(){
/**
* 方式 1
* list.stream();
*/
List<String> list = new ArrayList<>();
Stream<String> listStream = list.stream();
/**
* 方式 2
* Arrays.asList(arr).stream();
*/
String[] arr = new String[]{"hello","word","tom"};
Stream<String> arrStreamA = Arrays.asList(arr).stream();
/**
* 方式 3
* Stream.of(T t);
*/
Stream<String> stringStream = Stream.of("");
}
@Test
public void streamTest(){
Supplier<List<TeamUser>> supplierCreate = TeamUser::createTeamUserList;
/**
* 过滤名称长度小于3的用户
*/
supplierCreate.get().stream().filter(this::userInvoker).forEach(System.out::println);
System.out.println("======================================================================");
/**
* 过滤重复数据
* 自定义对象需要重写hashCode和equals方法
*/
supplierCreate.get().stream().distinct().forEach(System.out::println);
System.out.println("======================================================================");
/**
* 获取前N条记录
*/
supplierCreate.get().stream().limit(3).forEach(System.out::println);
System.out.println("======================================================================");
/**
* 舍弃前N条记录
*/
supplierCreate.get().stream().skip(5).forEach(System.out::println);
System.out.println("======================================================================");
/**
* 获取n~m之间的数据
* 例子 获取3~5的数据
*/
supplierCreate.get().stream().skip(3).limit(5-3).forEach(System.out::println);
System.out.println("======================================================================");
/**
* map操作,将元素转换
*/
List<String> collect = supplierCreate.get().stream().map(TeamUser::getName).collect(Collectors.toList());
System.out.println("======================================================================");
}
@Test
public void streamStopTest(){
Supplier<List<TeamUser>> supplierCreate = TeamUser::createTeamUserList;
/**
* 全局匹配,是否全部符合某条件,返回true or false
* stream().allMatch(Predicate<? super T> predicate);
* 例如:所有用户年龄是否都大于10岁
*/
boolean b = supplierCreate.get().stream().allMatch(e -> e.getAge()>10);
logger.info("所有用户年龄是否都大于10岁?{}",b?"yes":"no");
/**
* 精确匹配:是否存在符合某条件记录
* stream().anyMatch(Predicate<? super T> predicate);
* 例:
* 1、用户中是否存在姓名叫易大师的人
* 2、用户中是否有姓 德莱的人
*/
boolean b1 = supplierCreate.get().stream().anyMatch(e -> e.getName().equals("易大师"));
logger.info("易大师是否在用户列表中?{}",b1?"yes":"no");
boolean b2 = supplierCreate.get().stream().anyMatch(e -> e.getName().startsWith("德莱"));
logger.info("用户中是否有姓 德莱的人?{}",b2?"yes":"no");
boolean b3 = supplierCreate.get().stream().anyMatch(e -> e.getName().startsWith("胡"));
logger.info("用户中是否有姓 胡的人?{}",b3?"yes":"no");
logger.info("==========================================================================");
/**
* 全局不匹配:所有数据是否都不满足条件
* stream().noneMatch(Predicate<? super T> predicate)
* 例1:用户是否都不姓胡
* 例2:用户是否都小于40岁
* 例3:用户工资是否都大于3000
*/
boolean b4 = supplierCreate.get().stream().noneMatch(e -> e.getName().startsWith("胡"));
logger.info("用户是否都不姓胡?{}",b4?"yes":"no");
boolean b5 = supplierCreate.get().stream().noneMatch(e -> e.getAge()<40);
logger.info("用户是否都小于40岁?{}",b5?"yes":"no");
boolean b6 = supplierCreate.get().stream().noneMatch(e -> e.getSal()<3000);
logger.info("用户工资是否都不大于3000?{}",b6?"yes":"no");
logger.info("==========================================================================");
/**
* 统计集合中用户数量
* stream().count()
*/
long count = supplierCreate.get().stream().count();
logger.info("用户总数:{}",count);
logger.info("==========================================================================");
/**
* 从集合中随机获取元素
* stream().findAny()
*/
Optional<TeamUser> any = supplierCreate.get().stream().findAny();
logger.info(any.get().toString());
logger.info("==========================================================================");
/**
* 从集合中获取第一个元素
* stream().findFirst()
*/
Optional<TeamUser> first = supplierCreate.get().stream().findFirst();
logger.info(first.get().toString());
logger.info("==========================================================================");
/**
* 获取用户集合中的最大工资
* stream().max((Comparator<? super T> comparator)
*/
Optional<Double> max = supplierCreate.get().stream().map(e -> e.getSal()).max(Double::compareTo);
logger.info("用户中的最大工资数是{}",max.get());
logger.info("==========================================================================");
/**
* 获取用户集合中的年龄最小的员工
* stream().min((Comparator<? super T> comparator)
*/
Optional<TeamUser> min = supplierCreate.get().stream().min((e1, e2) -> Integer.compare(e1.getAge(), e2.getAge()));
logger.info("年龄最小的员工:{}",min.get());
logger.info("==========================================================================");
/**
* 排序:
* 1、默认排序 sorted()
* 2、自定义排序 sorted(Comparator<? super T> comparator)
*/
//例1:员工工资默认排序
supplierCreate.get().stream().map(e->e.getSal()).sorted().forEach(System.out::println);
//例2:员工按年龄正序排序
supplierCreate.get().stream().sorted((e1,e2)->Integer.compare(e1.getAge(),e2.getAge())).forEach(System.out::println);
logger.info("*********************");
//例3:员工按年龄倒序排序
supplierCreate.get().stream().sorted((e1,e2)->Integer.compare(e2.getAge(),e1.getAge())).forEach(System.out::println);
logger.info("==========================================================================");
/**
* 依靠排序+其他操作完成 求最大、最小需求
*/
//求工资最大金额
Optional<Double> aDouble = supplierCreate.get().stream().map(e -> e.getSal()).sorted((e1,e2)->Double.compare(e2,e1)).findFirst();
logger.info("用户中的最大工资数是{}",aDouble.get());
//求年龄最小员工
Optional<TeamUser> first1 = supplierCreate.get().stream().sorted((e1, e2) -> Integer.compare(e1.getAge(), e2.getAge())).findFirst();
logger.info("年龄最小的员工:{}",first1.get());
//求年龄最大员工
Optional<TeamUser> first2 = supplierCreate.get().stream().sorted((e1, e2) -> Integer.compare(e2.getAge(), e1.getAge())).findFirst();
logger.info("求年龄最大员工:{}",first2.get());
logger.info("==========================================================================");
/**
* 获取集合,通俗讲就是集合经过流式处理,再聚合为集合
* stream().collect(Collector<? super T, A, R> collector);
* 例:获取所有人员姓名,再以list返回
*/
supplierCreate.get().stream().map(TeamUser::getName).distinct().collect(Collectors.toList()).forEach(System.out::println);
}
private boolean userInvoker(TeamUser user){
return user.getName().length()<3;
}
}
标签:java,stream,get,用法,public,supplierCreate,TeamUser,logger,lambda
From: https://blog.csdn.net/huhongyong126/article/details/136869987