Stream流最佳实战
java
package com.al.admin.utils;
import cn.hutool.core.util.ObjectUtil;
import lombok.Data;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* 测试
*/
public class StreamUtil {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
for(int i=0; i<5 ;i++) {
Student student = new StreamUtil().new Student();
student.setId(i+"");
if(i > 2) {
student.setAge(1);
} else {
student.setAge(2);
}
if(i > 3) {
student.setName("zhangsan");
} else if(i == 0) {
student.setName(null);
} else {
student.setName("lisi");
}
student.setMoney(i);
student.setCreatedDate(null);
students.add(student);
}
//多级进行分组 当然也可以进行其他的操作
Map<String, Map<Integer, List<Student>>> collectq = students.stream()
.collect(Collectors.groupingBy(x -> StringUtils.isEmpty(x.getName()) ? "" : x.getName(), Collectors.groupingBy(Student::getAge)));
System.out.println("collectq:" + collectq);
SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
Map<String, List<Student>> groupBy = students.stream().collect(Collectors.groupingBy(a -> sm.format(a.getCreatedDate())));
System.out.println("==============");
System.out.println(groupBy);
/**
* 条件过滤
*/
System.out.println("条件过滤==============");
System.out.println("student.getAge() >1 ==============");
List<Student> collect = students.stream().filter(student -> student.getAge() > -1).collect(Collectors.toList());
System.out.println(collect);
/**
* 正序排列
*/
System.out.println("正序排列==============");
collect = collect.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
System.out.println(collect);
/**
* 倒序排列
*/
System.out.println("倒序排列==============");
collect = collect.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
System.out.println(collect);
/**
* string 类型的字段 倒序排列
*/
System.out.println("string 类型的字段进行倒序排序 ==============");
collect = collect.stream().sorted(Comparator.comparing(Student::getId).reversed()).collect(Collectors.toList());
System.out.println(collect);
/**
* string 类型的字段 进行截取 倒序排列
*/
System.out.println("string 类型的字段进行倒序排序 ==============");
collect = collect.stream().sorted((o1,o2) -> {
try {
return Integer.parseInt(o2.getName().split("-")[1].substring(0,5)) - Integer.parseInt(o1.getName().split("-")[1].substring(0,5));
} catch (Exception e){
e.printStackTrace();
}
return 0;
}).collect(Collectors.toList());
System.out.println(collect);
/**
* 多字段倒序排序
*/
System.out.println("多字段倒序排序 ==============");
collect = collect.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getId).reversed()).collect(Collectors.toList());
System.out.println(collect);
/**
* 多字段条件
*/
System.out.println("age大于20 money大于3000的数据==============");
Predicate<Student> predicate1 = student -> student.getAge()>20;
Predicate<Student> predicate2 = student -> student.getMoney()>3000;
List<Student> collect1 = collect.stream().filter(predicate1.and(predicate2)).collect(Collectors.toList());
System.out.println(collect1);
/**
* 两个集合差集 、 并集 、 交集
* 集合 students 、 collect
*/
System.out.println("两个集合差集");
Predicate<Student> predicate =
user -> collect1.stream()
.noneMatch(user1 -> (user.getId()).equalsIgnoreCase(user1.getId()));
collect = students.stream().filter(predicate).collect(Collectors.toList());
System.out.println("students - collect1的差集 注意 集合a对集合b之间的差集 和 集合b对集合a之间的差集 不一样");
System.out.println(collect);
System.out.println("两个集合交集");
Predicate<Student> predicate3 =
user -> collect1.stream()
.anyMatch(user1 -> (user.getId()).equalsIgnoreCase(user1.getId()));
collect = students.stream().filter(predicate3).collect(Collectors.toList());
System.out.println("students - collect1的交集");
System.out.println(collect);
System.out.println("两个集合并集");
List<Student> collect2 = students.parallelStream().collect(Collectors.toList());
List<Student> collect3 = collect1.parallelStream().collect(Collectors.toList());
collect2.addAll(collect3);
List<Student> collect4 = collect2.stream().distinct().collect(Collectors.toList());
System.out.println(collect4);
System.out.println("list 转 map");
System.out.println("key是list对象中id,value是list对象中的年龄");
Map<String, Integer> map = students.stream().collect(Collectors.toMap(Student::getId, Student::getAge));
System.out.println(map);
System.out.println("key是list对象中id,value是list对象");
Map<String, Student> map1 = students.stream().collect(Collectors.toMap(Student::getId, student -> student));
System.out.println(map1);
System.out.println("key是list对象中id,value是list对象 另一种写法");
Map<String, Student> map2 = students.stream().collect(Collectors.toMap(Student::getId, Function.identity()));
System.out.println(map2);
System.out.println("key是对象中的某个属性值,value是对象本身,当key冲突时选择第二个key值覆盖第一个key值。");
Map<String, Student> map3 = students.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (oldValue, newValue) -> newValue));
System.out.println(map3);
System.out.println("map 转 list");
List<String> collect5 = map3.keySet().stream().collect(Collectors.toList());
List<Student> collect6 = map3.values().stream().collect(Collectors.toList());
System.out.println("map的key转list::"+collect5);
System.out.println("map的value转list::"+collect6);
List<Student> lst = map.entrySet().stream().map(c -> {
Student student = new StreamUtil().new Student();
student.setId(c.getKey());
student.setAge(c.getValue());
return student;
}).collect(Collectors.toList());
System.out.println("通过map的key,value转对象集合");
System.out.println(lst);
}
@Data
public class Student {
private String id;
private int age;
private double money;
private String name;
private Date createdDate;
public Student(){
}
}
}
java
3、stream排序
java
public void test6() {
List<User> list = new ArrayList<>();
//定义三个用户对象
User user1 = new User();
user1.setUserName("admin");
user1.setAge(16);
user1.setSex("男");
User user2 = new User();
user2.setUserName("root");
user2.setAge(20);
user2.setSex("女");
User user3 = new User();
user3.setUserName("admin");
user3.setAge(18);
user3.setSex("男");
User user4 = new User();
user4.setUserName("admin11");
user4.setAge(22);
user4.setSex("女");
System.out.println(list);
// 年龄排序(逆序)
List<User> collect = list.stream().sorted(Comparator.comparing(User::getAge).reversed()).collect(Collectors.toList());
System.out.println(collect);
// 写法2
List<User> collect1 = list.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder())).
collect(Collectors.toList());
System.out.println(collect1);
// lambda表达式
List<User> collect2 = list.stream().sorted((a, b) -> b.getAge() - a.getAge()).collect(Collectors.toList());
System.out.println(collect2);
// 并行排序 - 排序数量大时使用并行排序,提高排序速度
list.parallelStream().sorted().collect(Collectors.toList());
// 多字段排序1-都进行倒序排序(先根据年龄倒序,再根据用户名倒序)
List<User> collect3 = list.stream().sorted(Comparator.comparing(User::getAge).
thenComparing(User::getUserName).reversed()).collect(Collectors.toList());
System.out.println(collect3);
// 多字段排序2-先根据年龄逆序,再根据用户名顺序--reversed()是让他前面所有字段进行倒序
list.stream().sorted(Comparator.comparing(User::getAge).reversed().
thenComparing(User::getUserName)).collect(Collectors.toList());
// 多字段排序3
list.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder()).
thenComparing(User::getUserName, Comparator.reverseOrder())).collect(Collectors.toList());
}