1.匿名内部类
就是new一个接口的实现,简写
public class LambdaDemo01 {
public static void main(String[] args) {
int i = calculateNum(new IntBinaryOperator() {
@Override
public int applyAsInt(int left, int right) {
return left + right;
}
});
System.out.println(i);
}
/**
* 方法传一个匿名内部类,方法实现自己写
* @param operator
* @return
*/
public static int calculateNum(IntBinaryOperator operator){
int a = 10;
int b = 20;
return operator.applyAsInt(a, b);
}
}
2.Stream流的创建
单列集合:ArrayList,数组。Stream.of
map集合就转化为set集合,map.entrySet()
准备工作:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Author {
private Long id;
private String name;
private int age;
private String intro;
private List<Book> books;
public static List<Author> getAuthors() {
Author author = new Author(1L, "蒙多", 33, "一一个从菜刀中明悟哲理的祖安人", null);
Author author2 = new Author(2L,
"亚拉索", 15, " 狂风也追逐不上他的思考速度", null);
Author author3 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);
Author author4 = new Author(3L, "易", 14, "是这个世界在限制他的思维", null);
//书籍列表
List<Book> books1 = new ArrayList<>();
List<Book> books2 = new ArrayList<>();
List<Book> books3 = new ArrayList<>();
books1.add(new Book(1L, "力的两侧是光明与黑暗", "哲学,爱情", 88, "用把刀划分了爱恨"));
books1.add(new Book(2L, "一个人不能死在同一把刀下", "个人成长,爱情", 99, "讲述如何从失败中明悟真理"));
books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));
books2.add(new Book(3L, "那风吹不到的地方", "哲学", 85, "带你用思维去领略世界的尽头"));
books2.add(new Book(4L, "吹或不吹", "爱情,个人传记", 56, "一个哲学家的恋爱观注定很难把他所在的时代理解"));
books3.add(new Book(5L, "你的剑就是我的剑", "爱情", 56, "无法想象一 个武者能对他的伴侣这么的宽容"));
books3.add(new Book(6L, "风与剑", "个人传记", 100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢? "));
books3.add(new Book(6L, "风与剑", "个人传记", 100, "两个哲学家灵魂和肉体的碰撞会激起怎么样的火花呢? "));
author.setBooks(books1);
author2.setBooks(books2);
author3.setBooks(books3);
author4.setBooks(books3);
List<Author> authorlist = new ArrayList<>(Arrays.asList(author, author2, author3, author4));
return authorlist;
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {
private Long id;
//书名
private String name ;
//分类
private String category;
//评分
private Integer score ;
private String intro;
}
3.中间操作
1.filter
对stream流进行过滤
public class StreamFilter {
public static void main(String[] args) {
List<Author> authors = Author.getAuthors();
//打印年龄小于18的作家名字
authors.stream().distinct()
.filter((author) -> author.getAge() < 18)
.forEach(author -> System.out.println(author.getName())
);
//打印所有姓名大于1的作家名字
authors.stream().filter(author -> author.getName().length() > 1).forEach(author -> System.out.println(author.getName()));
}
}
2.map
对stream流进行映射
对作者的名字进行映射,把作者list流变为String的list流
public class StreamMap {
public static void streamMap(){
Author.getAuthors().forEach(author -> System.out.println(author.getName()));
//打印所有作家的姓名
Author.getAuthors().stream().forEach(author -> System.out.println(author.getName()));
Author.getAuthors().stream()
.map(author -> author.getName())
.forEach(name -> System.out.println(name));
}
}
3.distinct
去重
public class StreamDistinct {
/**
* 打印所有作家的名字,不能有重复元素
*/
@Test
public void streamDistinct(){
Author.getAuthors().stream()
.distinct()
.forEach(author -> System.out.println(author.getName()));
}
}
4.sorted
排序
public class StreamSorted {
/**
* 按年龄降序排序,不能重复
*/
@Test
public void test(){
Author.getAuthors().stream().distinct()
.sorted()
.forEach(author -> System.out.println(author.getAge()));
Author.getAuthors().stream().distinct()
.sorted((o1, o2) -> o2.getAge() - o1.getAge())
.forEach(author -> System.out.println(author.getAge()));
}
}
5.skip
跳过
public class StreamSkip {
/**
* 打印处理年龄最大的作家外的其他作家。要求不能有重复元素,按年龄降序。
*/
@Test
public void test() {
Author.getAuthors().stream().distinct()
.sorted().skip(1)
.forEach(author -> System.out.println(author)
);
}
}
6.limit
public class StreamLimit {
/**
* 对元素按年龄降序排列,并不能有重复元素,打印年龄最大的两个作家的姓名
*/
@Test
public void test(){
Author.getAuthors().stream().distinct()
.sorted().limit(2)
.forEach(author -> System.out.println(author.getName()));
}
}
7.flatMap
转成其他对象流时发现转成了集合或者数组,这时候用flatMap
对象→集合→集合元素
public class StreamFlatMap {
/**
* 打印所有书籍的名字,并去重
*/
@Test
public void test() {
Author.getAuthors().stream()
//把作家对象流转换为书对象流
.flatMap(author -> author.getBooks().stream())
.distinct()
.forEach( book -> System.out.println(book.getName()));
}
/**
* 对象流,转数组流,再转对象流
* 打印现有书的所有分类,对分类进行去重
* */
@Test
public void test2() {
Author.getAuthors().stream()
.flatMap(author -> author.getBooks().stream())
.map(book -> book.getCategory().split(","))
.flatMap(book->Stream.of(book))
.distinct()
.forEach(category-> System.out.println(category));
}
}
4.终结操作
1.count
public class StreamCount {
/**
* 打印这些作家书籍的数目,删除重复元素
*/
@Test
public void test(){
System.out.println(
Author.getAuthors().stream().flatMap(author -> author.getBooks().stream())
.map(book -> book.getName())
.distinct().count()
);
}
}
2.min和max
public class StreamMinMax {
/**
* 获取作家所出书籍的最高分和最低分
*/
@Test
public void test(){
Optional<Integer> max = Author.getAuthors().stream().flatMap(author -> author.getBooks().stream())
.map(book -> book.getScore()).max((score1, score2) -> score1 - score2);
System.out.println(max.get());
}
}
3.collect
收集成list、set、map集合
map集合转stream流遍历
map集合直接遍历
public class StreamCollect {
/**
* 获取存放作者名字的List集合
*/
@Test
public void test() {
List<String> list = Author.getAuthors().stream()
.map(author -> author.getName())
.collect(Collectors.toList());
}
/**
* 获取所有书名的Set集合
*/
@Test
public void test1() {
Author.getAuthors().stream().flatMap(author -> author.getBooks().stream())
.map(book -> book.getName())
.collect(Collectors.toSet());
}
/**
* 获取所有书名的Map集合,key为作者名,value为List<Book>
*/
@Test
public void test2() {
Map<String, List<Book>> map = Author.getAuthors().stream()
.distinct()
.collect(Collectors.toMap(author -> author.getName(), author -> author.getBooks()));
map.forEach((key, value) -> System.out.println(key + ":" + value));
System.out.println("map.entrySet().stream.forEach()遍历—Stream流遍历");
map.entrySet()
.stream().forEach((Map.Entry<String, List<Book>> entry) -> {
System.out.print(entry.getKey()+":");
System.out.println(entry.getValue());
});
System.out.println("map.keySet().stream.forEach()遍历—Stream流遍历");
map.keySet().stream().forEach(key -> {
System.out.println(map.get(key));
});
//将map转换为list再遍历
map.entrySet().stream()
.flatMap(entry -> entry.getValue().stream()).forEach(book -> System.out.println(book.getName()));
}
}
4.查找与匹配
1.anyMatch
匹配任何一个,只要有一个符合要求就返回true
public class StreamAnyMatch {
/**
* 判断是否有年龄在29以上的作家
*/
@Test
public void test() {
boolean b = Author.getAuthors().stream().anyMatch(author -> author.getAge() > 29);
}
}
2.allMatch
全匹配
public class StreamAllMatch {
/**
* 判断作家是否都是成年人
*/
@Test
public void test() {
boolean b = Author.getAuthors().stream().allMatch(author -> author.getAge() > 18);
}
}
3.noneMatch
全不匹配
public class StreamNoneMatch {
/**
* 判断是否都没有100岁以上的作家
*/
@Test
public void test() {
boolean b = Author.getAuthors().stream().noneMatch(author -> author.getAge() > 100);
}
}
4.findFirst
public class StreamFindFirst {
/**
* 获取任意一个年龄大于18的作家,输出第一个名字
*/
@Test
public void test() {
Optional<Author> optional = Author.getAuthors().stream()
.filter(author -> author.getAge() > 18).findFirst();
optional.ifPresent(author -> System.out.println(author.getName()));
}
}
5.findAny
public class StreamFindAny {
/**
* 获取任意一个年龄大于18的作家,如果存在就输出他的名字
*/
@Test
public void test() {
Optional<Author> optional = Author.getAuthors().stream().filter(author -> author.getAge() > 18).findAny();
optional.ifPresent(author -> System.out.println(author.getName()));
}
}
5.归并
两个参数比一个参数多了个初始值
*/
public class StreamReduce {
/**
* 求作者年龄的和
*/
@Test
public void test() {
Integer sum = Author.getAuthors().stream().distinct()
.map(author -> author.getAge())
// 初始化 ,(当前值,匹配的值) result=result+age
.reduce(0, (result, age) -> result + age);
}
/**
* 求作者年龄最大值
*/
@Test
public void test1() {
Integer sum = Author.getAuthors().stream().distinct()
.map(author -> author.getAge())
.reduce(Integer.MIN_VALUE, (result, age) -> result > age ? result : age);
}
}
6.并行流
应用于多线程场景,parallel