今天对这些内容进行了一个复习,以写demo加做笔记的形式
stream能够更加优雅的处理集合、数组等数据,让我们写出更加直观、可读性更高的数据处理代码
创建steam流的方式
set、list能够直接通过.stream()的形式创建steam流
而数组需要通过 Arrays.stream(arr); Stream.of(arr);
map需要通过entrySet()方法,先将map转换成Set<Map.Entry<String, Integer>> set对象,再通过set.stream()的方式转换
stream中的api比较多
/**
* @author Pzi
* @create 2022-12-30 13:22
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class Test2 {
@Test
public void test1() {
List<Author> authors = S.getAuthors();
authors
.stream()
.distinct()
.filter(author -> {
// 满足这个条件,那么才会被筛选到继续留在stream中
return author.getAge() < 18;
})
.forEach(author -> System.out.println(author.getAge()));
}
// 对双列集合map的stream操作
@Test
public void test2() {
Map<String, Integer> map = new HashMap<>();
map.put("蜡笔小新", 19);
map.put("黑子", 17);
map.put("日向翔阳", 16);
//entrySet是一个包含多个Entry的Set数据结构,Entry是key-val型的数据结构
Set<Map.Entry<String, Integer>> entries = map.entrySet();
entries.stream()
.filter(entry -> {
return entry.getValue() > 17;
})
.forEach(entry -> {
System.out.println(entry);
});
}
// stream的map操作,提取stream中对象的属性,或者计算
@Test
public void test3() {
List<Author> authors = S.getAuthors();
authors
.stream()
.map(author -> author.getName())
.forEach(name -> System.out.println(name));
System.out.println(1);
authors
.stream()
.map(author -> author.getAge())
.map(age -> age + 10)
.forEach(age -> System.out.println(age));
}
// steam的sorted操作
@Test
public void test4() {
List<Author> authors = S.getAuthors();
authors
.stream()
.distinct()
.sorted(((o1, o2) -> o2.getAge() - o1.getAge()))
.skip(1)
.forEach(author -> System.out.println(author.getName() + " " + author.getAge()));
}
// flapMap的使用,重新组装,改变stream流中存放的对象
@Test
public void test5() {
// 打印所有书籍的名字。要求对重复的元素进行去重。
List<Author> authors = S.getAuthors();
authors.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.forEach(book -> System.out.println(book.getName()));
authors.stream()
// 将以authors为对象的stream流 组装成 以book为对象的strem流
.flatMap(author -> author.getBooks().stream())
.distinct()
// 将每个book中的category转换成数组,然后将[x1,x2]代表分类的数组转换成stream流,然后使用flapMap将该数组stream流组装成以x1,x2...为对象的stream流
// 将以book为对象的strem流 组装成 以category为对象的stream流
.flatMap(book -> Arrays.stream(book.getCategory().split(",")))
.distinct()
.forEach(category -> System.out.println(category));
}
// 数组转换成stream流
@Test
public void test6() {
Integer[] arr = {1, 2, 3, 4, 5};
Stream<Integer> stream = Arrays.stream(arr);
stream
.filter(integer -> integer > 3)
.forEach(integer -> System.out.println(integer));
}
@Test
public void test7() {
// 打印这些作家的所出书籍的数目,注意删除重复元素。
List<Author> authors = S.getAuthors();
long count = authors
.stream()
.flatMap(author -> author.getBooks().stream())
.distinct()
.count();
System.out.println(count);
}
// max() min()
@Test
public void test8() {
// 分别获取这些作家的所出书籍的最高分和最低分并打印。
List<Author> authors = S.getAuthors();
Optional<Integer> max = authors.stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore())
.max((score1, score2)