利用Lambda 流的方式来用最简洁精炼的代码实现我们所需要的功能
程序员文章站
2022-04-08 21:39:40
...
Lambda 表达式
Lambda 表达式,用最简易的方法来实现功能
用流来实现功能
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
/**
* Stream是数据的处理, 并不保存数据, Stream只能用一次
* 三个步骤:
* 1) 创建流
* 1) 基于集合获取流
* 集合对象.stream()
* 2) 基本数组获取流
* Arrays.stream(数组对象)
* 3) 基于散列数据
* Stream.of(T... 对象列表)
* 4) 其他
* Stream.generate(Supplier sup); 无限流
*
* 2) 中间操作(可以有多个, 一系列的操作)
* filter(判定器) 把流中的所有对象都经过判定器, 如果判定结果为true, 留下.
* distinct() 去重, 依据是equals和hashCode
* limit(long maxSize) 截断流
* skip(long n) 略过n个元素, 通常会和limit配合.
* map(转换器) 把流中的所有对象都经过转换器转换成另外的对象.
*
* 3) 中止流
* forEach(消费器) 把流中的所有对象都经过消费器.
* reduce(二元运算) 把流中的对象两两处理产生新对象,依次再和后面的对象两两处理. 最终的结果就一个.
* collect(整除器)
*
* Optional 避免空指针 , 内部使用属性保存一个引用
* 调用orElse方法可以避免空指针
*/
public class StreamTest {
@Test
public void testName9() throws Exception {
List<Student> collect = StudentData.getList().parallelStream().distinct().filter(t -> t.getGrade() == 3).collect(Collectors.toList());
for (Student student : collect) {
System.out.println(student);
}
}
@Test
public void testName8() throws Exception {
// 获取全校总分
Optional<Double> reduce = StudentData.getList().stream().distinct().map(t -> t.getScore()).reduce((t1, t2) -> t1 + t2);
Double orElse = reduce.orElse(-1.0);
System.out.println(orElse);
}
@Test
public void testName7() throws Exception {
long count = StudentData.getList().stream().distinct().count();
System.out.println(count);
}
@Test
public void testName6() throws Exception {
Optional<Student> first = StudentData.getList().stream().distinct().filter(t -> t.getScore() > 90).findFirst();
Student stu = first.orElse(new Student(1, "傀偘", 1, 0));
System.out.println(stu); // 永远不会空指针
}
// 找出三年级没有及格的2名同学, 倒序打印输出
@Test
public void testName5() throws Exception {
StudentData.getList().stream().distinct()
.filter(t -> t.getGrade() == 3).filter(t -> t.getScore() < 60)
.sorted((t1, t2) -> (int)(t2.getScore() - t1.getScore()))
.limit(2).forEach(System.out::println);
}
@Test
public void testName4() throws Exception {
StudentData.getList().stream().distinct().sorted((t1, t2) -> t1.getGrade() - t2.getGrade()).forEach(System.out::println);
}
@Test
public void testName3() throws Exception {
StudentData.getList().stream().distinct().sorted().forEach(System.out::println);
}
// 把所有3年级没有及格的同学转换成String, 内容是"姓名 + 分数"
@Test
public void test9() {
StudentData.getList().stream().distinct()
.filter(t -> t.getGrade() == 3).filter(t -> t.getScore() < 60)
.map(t -> t.getName() + t.getScore())
.forEach(System.out::println);
}
@Test
public void testName2() throws Exception {
StudentData.getList().stream().distinct().map(t -> t.getScore()).forEach(System.out::println);
}
@Test
public void testName() throws Exception {
StudentData.getList().stream().distinct().skip(10).limit(5).forEach(System.out::println);
}
@Test
public void test8() {
StudentData.getList().stream().distinct().filter(t -> t.getGrade() == 3).filter(t -> t.getScore() < 60).forEach(System.out::println);
}
// 找出姓王的没有及格的同学
@Test
public void test7() {
StudentData.getList().stream().filter(t -> t.getName().startsWith("王")).filter(t -> t.getScore() < 60).forEach(System.out::println);
}
@Test
public void test6() {
StudentData.getList().stream().filter(t -> t.getGrade() == 3).filter(t -> t.getScore() < 60).forEach(System.out::println);
}
@Test
public void test5() {
Stream<Student> stream = StudentData.getList().stream();
//Stream<Student> filter = stream.filter(t -> t.getGrade() == 2);
//filter.forEach(System.out::println);
Stream<Student> filter = stream.filter(t -> t.getGrade() == 6);
Stream<Student> filter2 = filter.filter(t -> t.getScore() < 60);
filter2.forEach(System.out::println);
}
@Test
public void test4() {
// 无限流
Stream<Double> generate = Stream.generate(Math::random);
generate.forEach(System.out::println);
}
@Test
public void test3() {
Stream<String> of = Stream.of("ac", "xx", "293", "alksj");
of.forEach(System.out::println);
}
@Test
public void test2() {
Integer[] arr = {3, 2, 1, 0, 9, 8};
Stream<Integer> stream = Arrays.stream(arr);
stream.forEach(System.out::println);
}
@Test
public void test1() {
List<Student> list = StudentData.getList();
Stream<Student> stream = list.stream();
stream.forEach(System.out::println);
}
}
对实体类的简单操作
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class StudentData {
public static List<Student> getList() {
List<Student> list = new ArrayList<>(); // 根据左面的泛型可以推断右边的泛型 , 称为类型推断.
String[] names1 = {"张", "王", "李", "杨", "罗", "赵", "刘", "韩"};
String[] names2 = {"伟", "丽", "刚", "龙", "琳", "凤", "丹", "宇", "健", "霞"};
for (int i = 0; i < 20; i++) {
int id = i + 1;
int index1 = (int)(Math.random() * 100) % names1.length;
int index2 = (int)(Math.random() * 100) % names2.length;
String name = names1[index1] + names2[index2];
int grade = (int)(Math.random() * 6 + 1);
double score = (int)(Math.random() * 101);
list.add(new Student(id, name, grade, score));
}
list.add(new Student(50, "小明", 3, 100));
list.add(new Student(50, "小明", 3, 40));
list.add(new Student(50, "小明", 3, 40));
list.add(new Student(50, "小明", 3, 40));
list.add(new Student(50, "小明", 3, 40));
list.add(new Student(50, "小明", 3, 40));
for (Student stu : list) {
System.out.println(stu);
}
System.out.println("**************************************************");
return list;
}
/*
* 创建一个集合, 保存20个学生对象, 年级随机的[1~6], 分数是随机的[0~100]
再添加几个固定的学生, 所有属性值都一样.
找出三年级没有及格的2名同学, 倒序打印输出*/
public static void main(String[] args) {
List<Student> list = getList();
// 找出三年级没有及格的2名同学, 倒序打印输出
List<Student> list2 = new ArrayList<>();
for (Student student : list) {
if (student.getGrade() == 3) {
list2.add(student);
}
}
List<Student> list3 = new ArrayList<>();
for (Student student : list2) {
if (student.getScore() < 60) {
list3.add(student);
}
}
for (Student student : list3) {
System.out.println(student);
}
System.out.println("**************************************************");
Set<Student> set = new HashSet(list3);
List<Student> list4 = new ArrayList(set);
Collections.sort(list4);
Collections.reverse(list4);
List<Student> list5 = new ArrayList<>();
for (Student student : list4) {
list5.add(student);
if (list5.size() == 2) {
break;
}
}
System.out.println("**************************************************");
for (Student student : list5) {
System.out.println(student);
}
}
}
实体类
public class Student implements Comparable<Student> {
private in
t id;
private String name;
private int grade;
private double score;
public Student() {
}
public Student(int id, String name, int grade, double score) {
super();
this.id = id;
this.name = name;
this.grade = grade;
this.score = score;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", grade=" + grade + ", score=" + score + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + grade;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(score);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (grade != other.grade)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(score) != Double.doubleToLongBits(other.score))
return false;
return true;
}
@Override
public int compareTo(Student o) {
return (int)(this.score * 10 - o.score * 10);
}
}