2023年12月19日,随笔练习stream流
package com.hs.stram;
import com.hs.stram.entity.Student;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* @author HK
*/
public class StreamLearning {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
//使用find查找第一个元素
Optional<Integer> first = list.stream().findFirst();
System.out.println("find查找第一个元素:" + first.get());
//使用match,判断是否存在某个值
boolean b = list.stream().anyMatch(integer -> integer > 10);
System.out.println("大于10是否存在:" + b);
boolean b2 = list.stream().anyMatch(integer -> integer == 10);
System.out.println("10是否存在:" + b2);
//使用foreach遍历数据
list.stream().forEach(integer -> System.out.print(integer));
System.out.println();
list.stream().forEach(System.out::print);
System.out.println();
//filter使用:筛选大于5的并输出
list.stream().filter(integer -> integer > 5).forEach(System.out::print);
System.out.println();
//筛选对象 年纪大于20的学生输出
List<Student> students = getStudents();
students.stream().filter(student -> student.getAge() > 20).forEach(System.out::print);
//性别为女生的,并输出
System.out.println();
students.stream().filter(student -> "女".equals(student.getSex())).forEach(System.out::print);
System.out.println();
//max min count 终结方法
Integer max = list.stream().max(Comparator.comparingInt(value -> value)).get();
System.out.println("最大值:" + max);
Integer min = list.stream().min((o1, o2) -> -o1 - o2).get();
System.out.println("最小值:" + min);
long count = list.stream().count();
System.out.println("总数为:" + count);
//map和flatmap
//收集学生对象的名字
students.stream().map(student -> student.getName()).forEach(System.out::print);
System.out.println();
students.stream().flatMap(student -> {
Stream<String> stream = Arrays.stream(student.toString().split("Student"));
return stream;
}).forEach(System.out::print);
System.out.println();
//reduce 求和 求极值 求乘积
Integer sum = list.stream().reduce(0, Integer::sum);
System.out.println("求和"+sum);
Integer reduceMin = list.stream().reduce(Integer::min).get();
System.out.println("求最小值"+reduceMin);
Integer reduceNax = list.stream().reduce(Integer::max).get();
System.out.println("求最大值"+reduceNax);
Integer product = list.stream().reduce((result, integer) -> result*integer).get();
System.out.println("求乘积"+product);
//收集collect toList toSet toMap
List<Integer> list2 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,10,4,5);
//大于5
List<Integer> toList = list2.stream().filter(integer -> integer > 5).collect(Collectors.toList());
//大于5去重
Set<Integer> toSet = list2.stream().filter(integer -> integer > 5).collect(Collectors.toSet());
//key为值,value拼接"大多数都是"
Map<Integer,String> toMap = list2.stream().distinct().filter(integer -> integer > 5).collect(Collectors.toMap(integer -> integer, integer -> integer+"大多数都是"));
System.out.println(toList);
System.out.println(toSet);
System.out.println(toMap);
List<Integer> list3 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 20, 37, 49, 243, 30);
// partitioningBy
Map<Boolean, List<Integer>> collect1 = list3.stream()
.collect(Collectors.partitioningBy(value -> value > 20));
System.out.println(String.format("元素值是否大于20进行分组,结果为:%s", collect1));
collect1.forEach((key, value) -> {
System.out.printf("元素值是否大于20进行分组,结果为:%s:%s", key, value);
});
System.out.println();
//groupingBy
List<User> userList = Arrays.asList(
new User(1, "xww", "女", 22),
new User(2, "zgx", "男", 21),
new User(3, "whb", "男", 23),
new User(4, "gg", "男", 30),
new User(5, "yda", "男", 22),
new User(6, "bhm", "女", 23),
new User(7, "lsn", "女", 22),
new User(8, "ksj", "女", 22),
new User(8, "ksj", "女", 22)
);
Map<String,List<User>> collect = userList.stream().collect(Collectors.groupingBy(User::getSex));
collect.forEach((s, users) -> System.out.println(users));
//排序
List<User> users = userList.stream().sorted((o1, o2) -> o1.getAge() - o2.getAge()).collect(Collectors.toList());
System.out.println("排序结果"+users);
//根据年龄去重
System.out.println(userList.stream().distinct().collect(Collectors.toList()));
//注意stream包含拆装箱,浪费性能 可以使用mapToInt转为int或者map都行
list3.stream().mapToInt(new ToIntFunction<Integer>() {
@Override
public int applyAsInt(Integer value) {
return value;
}
}).forEach(new IntConsumer() {
@Override
public void accept(int value) {
System.out.println(value);
}
});
}
private static void test4() {
List<Student> list = getStudents();
/**
* [10, 20, 30, 40]
*/
//获取对象属性为list类型的属性的每一个数据转为一个对象去重并输出
list.stream().map(student -> student.getScore()).distinct().forEach(list1 -> System.out.println(list1));
// 10 20 30 40 10 20 30 40 10 20 30 40 10 20 30 40 10 20 30 40 10 20 30 40
list.stream().flatMap((Function<Student, Stream<Integer>>) student -> student.getScore().stream()).distinct().forEach(integer -> System.out.print(integer + " "));
}
private static void test03() {
List<Student> list = getStudents();
//skip方法 跳过前n个元素
list.stream().distinct().sorted((o1, o2) -> o2.getAge() - o1.getAge()).skip(1).forEach(student -> System.out.println(student));
}
private static void test2() {
List<Student> list = getStudents();
//去重根据年纪降序,分页取3
list.stream()
.distinct()
.sorted((o1, o2) -> o2.getAge() - o1.getAge()).limit(3).forEach(student -> System.out.println(student.getAge()));
}
private static void test1() {
List<Student> list = getStudents();
list.stream().filter(student -> student.getAge() > 20).forEach(student -> System.out.println(student.getAge()));
list.stream().distinct().forEach(student -> System.out.println(student));
//去重 排序根据年龄 空参的sorted需要类实现Comparable接口重写compareTo方法
list.stream().distinct()
.sorted()
.forEach(student -> System.out.println(student.getAge()));
list.stream().distinct().sorted((o1, o2) -> o1.getAge() - o2.getAge()).forEach(student -> System.out.println(student.getAge()));
}
private static List<Student> getStudents() {
List<Integer> asList = Arrays.asList(10, 20, 30, 40);
Student student1 = new Student("Alice", 18, "男", asList);
Student student2 = new Student("Bob", 19, "女", asList);
Student student3 = new Student("Charlie", 20, "男", asList);
Student student4 = new Student("David", 21, "男", asList);
Student student5 = new Student("Eric", 22, "女", asList);
Student student6 = new Student("Eric", 22, "男", asList);
List<Student> list = Arrays.asList(student1, student2, student3, student4, student5, student6);
return list;
}
}
涉及的类
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class User {
private int id;
private String name;
private String sex;
private int age;
}
package com.hs.stram.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import java.time.Instant;
import java.util.Comparator;
import java.util.List;
/**
* @author HK
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
public class Student implements Comparable<Student> {
private String name;
private int age;
private String sex;
private List<Integer> score;
@Override
public int compareTo(Student o) {
return -this.getAge()+o.getAge();
}
}
pom.xml文件导入坐标
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>