Java8新特性Streams常用API案例详解
Posted 醉酒的小男人
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java8新特性Streams常用API案例详解相关的知识,希望对你有一定的参考价值。
Stream的操作分为中间操作和晚期操作,中间操作是返回新的Stream,只是记录下操作,不会真的执行;晚期操作是真的执行遍历列表并执行所有操作。Stream可以支持并行执行parallel 方法。
code
public class User {
private Integer id;
private String name;
private String pass;
private String sex;
private Integer age;
private String auth;
public User(){
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User(Integer id, String name, String pass, String sex, Integer age, String auth) {
this.id = id;
this.name = name;
this.pass = pass;
this.sex = sex;
this.age = age;
this.auth = auth;
}
public String getAuth() {
return auth;
}
public void setAuth(String auth) {
this.auth = auth;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\\'' +
", pass='" + pass + '\\'' +
", sex='" + sex + '\\'' +
", age=" + age +
'}';
}
public static List<User> getUserList(){
List<User> users = new ArrayList<>();
User user1 = new User(1,"zhangsan1","aaa","男",18,"1,2,3,4");
User user2 = new User(2,"zhangsan2","bbb","男",19,"5,6,7,8");
User user3 = new User(3,"zhangsan3","ccc","女",20,"9,10,11,12");
User user4 = new User(4,"zhangsan4","ddd","女",21,"14,15,16,17");
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
return users;
}
List<User> userList = getUserList();
遍历(foreach)
userList.forEach(item-> System.out.println(item.toString()));
System.out.println("==================forEach遍历List集合=================");
userList.forEach(System.out::println);
Map<String,String> map = new HashMap<String,String>();
map.put("11","11");
map.put("22","22");
System.out.println("==================forEach遍历Map==================");
map.forEach((k,v)-> System.out.println(k+","+v));
匹配(findFirst/findAny/anyMatch)
Optional<User> findFirst = userList.stream().filter(item->item.getAge() >18).findFirst();
System.out.println("匹配第一个:"+findFirst.get());
Optional<User> findAny = userList.parallelStream().filter(item->item.getAge() >18).findAny();
System.out.println("匹配任意一个(适用于并行流):"+findAny.get());
boolean anyMatch = userList.stream().anyMatch(item->item.getAge() > 18);
System.out.println("是否有符合条件的元素:"+anyMatch);
聚合(max/min/count)
Optional<User> max = userList.stream().max(Comparator.comparingInt(User::getAge));
System.out.println("年龄最大值:"+max.get().getAge());
Optional<User> min = userList.stream().min(Comparator.comparingInt(User::getAge));
System.out.println("年龄最小值:"+min.get().getAge());
long count = userList.stream().filter(a->a.getAge() > 19).count();
System.out.println("总个数:"+count);
筛选(filter)
//查询年龄大于20的数据
List<User> users = userList.stream().filter(user -> user.getAge()>20).collect(Collectors.toList());
users.forEach(System.out::println);
映射(map/flatMap)
map
接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
String[] arr = {"aaa","bbb","ccc","ddd"};
List<String> upperCaseList = Stream.of(arr).map(String::toUpperCase).collect(Collectors.toList());
System.out.println("====================每个元素大写=======================");
upperCaseList.forEach(System.out::println);
List<String> appendList = Arrays.asList(arr).stream().map(str->str+"中国").collect(Collectors.toList());
System.out.println("=====================每个元素追加中国===================================");
appendList.forEach(System.out::println);
List<String> nameList = userList.stream().map(User::getName).collect(Collectors.toList());
System.out.println("================集合中单独取出一列=====================");
nameList.forEach(System.out::println);
每个年龄自动加5岁
List<User> ageList = userList.stream().map(user->{
return new User(user.getId(),user.getName(),user.getPass(),user.getSex(),user.getAge()+5,user.getAuth());
}).collect(Collectors.toList());
System.out.println("一次改动后年龄:"+ageList.get(0).getAge());
System.out.println("一次改动前年龄:"+userList.get(0).getAge());
List<User> ageList0 = userList.stream().map(user->{
user.setAge(user.getAge()+5);
return user;
}).collect(Collectors.toList());
System.out.println("二次改动后年龄:"+ageList0.get(0).getAge());
System.out.println("二次改动前年龄:"+userList.get(0).getAge());
flatMap
接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
查询出所有人的权限转成List
//查出所有人的所有权限
List<String> authList = userList.stream().map(u->{
String auths = u.getAuth();
return auths.split(",");
}).flatMap(Arrays::stream).collect(Collectors.toList());
System.out.println("=====================查询出所有人的权限转成List============================");
authList.forEach(System.out::println);
两个数组合并成一个数组
List<String> list = Arrays.asList("a,x,f","b,o");
List<String> listNew = list.stream().flatMap(s->{
String[] split = s.split(",");
Stream<String> s2 = Arrays.stream(split);
return s2;
}).collect(Collectors.toList());
System.out.println("处理前:"+list+",数组个数:"+list.size());
System.out.println("处理后:"+listNew+",数组个数:"+listNew.size());
List取两列组成map
Map<Integer,Integer> map = userList.stream().collect(Collectors.toMap(User::getId,User::getAge));
groupingBy分组
Map<String,List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getSex));
groupingBy分组求和
Map<String,Double> mapSum = userList.stream().collect(Collectors.groupingBy(User::getSex,Collectors.summingDouble(User::getAge)));
sort单列排序
//按年龄排序从大到小集合的sort
userList.sort((v1,v2)->v2.getAge().compareTo(v1.getAge()));
sorted单列降序
//stream处理不会改变列表需要返回使用reversed
List<User> collection = userList.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
thenComparing升序
//按age降序,按id升序
List<User> sortUserList = userList.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(Comparator.comparing(User::getId))).collect(Collectors.toList());
flatMap数据处理
//查出所有人的所有权限
List<String> authList = userList.stream().map(u->{
String auths = u.getAuth();
return auths.split(",");
}).flatMap(Arrays::stream).collect(Collectors.toList());
mapReduce处理数据
//计算所有年龄的和
Integer reduce = userList.stream().parallel().map(User::getAge).reduce(0,Integer::sum)
以上是关于Java8新特性Streams常用API案例详解的主要内容,如果未能解决你的问题,请参考以下文章