lambda
案例
案例1
new Threaad(new Runable(){
public void run(){
System.out.println("xxx"):
}
}).start();
new Thread(()->
{
System.out.println("xxx");
}
).star();
案例2
public static int calculateNum(IntBinaryOperator operator){
int a = 10;
int b = 200;
return operator.applyAsInt(a,b);
}
public void main(String[] args){
calculateNum( (a,b)-> a*b );
}
案例3
public static void printNum(Inpredicate predicate){
int[] arr = {1,2,3,4,5,6,7,8,9,10};
for(int i: arr){
if(predicate.test(i)){
System.out.println(i);
}
}
}
public void main(String[] args){
printNum(x->{
return x%2==0;
})
}
案例4
public static <R> R typeConver(Function<String,R> function){
String str = "12345";
R result = function.apply(str);
return result;
}
public void main(String[] args){
Integer result = typeConver(x->Integer.valueOf(x));
}
案例5
public static void foreachArr(IntConsumer consumer){
int[] arr = {1,2,3,4,5,6,7,8};
for(int i:arr){
consumer.accept(i);
}
}
public void main(String[] args){
foreachArr(x->System.out.println(x));
}
Stream
案例
- 数据准备
public class Author{
private Long id;
private String name;
private Integer age;
private String intro;
private List<Book> books;
}
public class Book{
private Long id;
private String name;
private String category;
private Integer score;
private String intro;
}
private static List<Autor> getAutors(){
Author a1 = new Author(1l,"xx",22,"xxx",null);
Author a2 = new Author(2l,"xx",33,"xxx",null);
Author a3 = new Author(3l,"xx",44,"xxx",null);
Author a4 = new Author(4l,"xx",55,"xxx",null);
List<Book> b1 = new ArrayList<>();
List<Book> b2 = new ArrayList<>();
List<Book> b3 = new ArrayList<>();
b1.add(new Book(1l,"xxxx","xxx",88,"xxxxxxxxx"));
b1.add(new Book(2l,"xxxx","xxx",89,"xxxxxxxxx"));
b1.add(new Book(3l,"xxxx","xxx",90,"xxxxxxxxx"));
b2.add(new Book(4l,"xxxx","xxx",91,"xxxxxxxxx"));
b2.add(new Book(5l,"xxxx","xxx",92,"xxxxxxxxx"));
b2.add(new Book(6l,"xxxx","xxx",95,"xxxxxxxxx"));
b3.add(new Book(7l,"xxxx","xxx",98,"xxxxxxxxx"));
b3.add(new Book(8l,"xxxx","xxx",99,"xxxxxxxxx"));
b3.add(new Book(9l,"xxxx","xxx",100,"xxxxxxxxx"));
a1.setBooks(b1);
a2.setBooks(b2);
a3.setBooks(b3);
a4.setBooks(b3);
List<Author> authorList = new ArrayList<>(Arrays.asList(a1,a2,a3,a4));
return authorList;
}
创建流
// 年龄小于18 去重 打印
List<Author> authors = getAuthors();
authors.stream()
.distinct()
.filter(x->x.getAge()<18)
.forEach(x->System.out.println(x.getName()));
// 数组创建
Integer[] arr = {1,2,3,4,5};
Arrays.stream(arr).distinct().forEach(x->System.out.println(x));
Stream.of(arr);
// Set
HashMap<String, String> map=new HashMap<>();
Set<Map.Entry<String, String>> set=map.entrySet();
set.stream();
// Map
Map map = new HashMap();
map.entrySet().stream();
中间操作
// filter
// 打印姓名长度大于1
authors.stream()
.filter(x->x.getName().length()>1)
.forEach(x->System.out.println(x.getName()));
// map
// 打印所有姓名
authors.stream().forEach(x->System.out.println(x.getName()));
authors.stream().map(x->x.getName()).forEach(x->System.out.println(x));
// distinct
// 打印所有姓名 去重
authors.stream().distinct().map(x->x.getName()).forEach(x->System.out.println(x));
// sorted
// 姓名去重 年龄排序
// implements Comparable<Author>
// public int compareTo(Author o){}
authors.stream().distinct().sorted((a,b)->a.getAge()-b.getAge()).forEach(x->System.out.println(x.getAge() ));
// limit
// 排序后限制2个
authors.stream().distinct().sorted((a,b)->a.getAge()-b.getAge())
.limit(2).forEach(x->System.out.println(x.getName() ));
// skip
// 排序 跳过1个
authors.stream().distinct().sorted((a,b)->b.getAge()-a.getAge()).skip(1).forEach(x->System.out.println(x.getName() ));
// flatMap
authors.stream().flatMap(x->x.getBooks().stream()).distinct().forEach(x->System.out.println(x.getName() );
终结操作
// forEach
authors.stream().forEach(x->System.out.println(x.getName()));
// count
authors.stream().flatMap(x->x.getBooks().stream())
.distinct().count();
// min max
authors.stream().distinct().flatMap(x->x.getBooks().stream()).map(x->x.getSocre()).max((a,b)->a-b).get();
authors.stream().distinct().flatMap(x->x.getBooks().stream()).map(x->x.getSocre()).min((a,b)->a-b).get();
// collect
// list
authors.stream().map(x->x.getName()).collect(Collectors.toList());
// set
authors.stream().map(x->x.getName()).collect(Collectors.toSet());
// map
authors.stream()
.collect(Collectors.toMap(x->x.getName(),x->x.getBooks())) ;
// anyMatch
authors.stream().anyMatch(x->x.getAge()>10);
// allMatch
authors.stream().allMatch(x->x.getAge()>10);
// noneMatch
authors.stream().noneMatch(x->x.getAge()>10);
// findAny
// 随机获取
authors.stream().filter(x->x.getAge()>18).findAny();
// findFirst
authors.stream().sorted((a,b)->a.getAge()-b.getAge()).findFirst();
// reduce
// 求和
authors.stream().distinct().map(x->x.getAge()).reduce(0,(a,b)->a+b);
// 最大值
authors.stream().distinct().map(x->x.getAge()).reduce(0,(a,b)->a>b?a:b);
authors.stream().distinct().map(x->x.getAge()).reduce((a,b)->a>b?a:b);
// 最小值
authors.stream().distinct().map(x->x.getAge()).reduce(100,(a,b)->a>b?b:a);
authors.stream().distinct().map(x->x.getAge()).reduce((a,b)->a>b?b:a);
optional
创建
// 不确定author是否为空
Optional<Author> op = Optional.ofNullable(author);
// 确定object不为空
Optional.of(object);
// 返回空
Optional.empty()''
操作
// 如果存在
op.ifPresent(x->System.out.println(x.getName()));
// 获取
// 如果没有 创建默认值
op.orElseGet(()->new Author());
// 如果没有 抛出异常
op.orElseThrow(()->new Exception("xxx"));
// 过滤
// 返回一个OPtional对象
op.fliter(x->x.getAge()>18);
// 判断
op.isPresent();
// 数据转换
op.map(x->x.getBooks())
.ifPresent(x->System.out.println(x.size());
函数式接口
-
注解
- @FunctionalInterface
-
接口
- Consumer
- void accept(T t)
- BiConsumer<T,U>
- void accept(T t,U u)
- Function<T,R>
- R apply(T t)
- BiFunction<T,U,R>
- R accept(T t,U u)
- Predicate
- boolean test(T t)
- BiPredicate<T,U>
- boolean accept(T t,U u)
- Supplier
- T get()
- BooleanSupplier
- boolean getAsBoolean()
- Consumer
-
默认方法
// Predicate<T> and()
authors.stream()
.filter((x->x.getAge()>17).and(x->x.getName().length()>1))
.forEach(x->System.out.println(x.getAge()));
// Predicate<T> negate()
// 取反
// 取不大于17
authors.stream()
.filter((x->x.getAge()>17).negate())
.forEach(x->System.out.println(x.getAge()));
方法引用
- 类名或对象名::方法名
- 不会的话可以使用idea自动生成。。。
数据类型转换
// mapToInt
authors.stream()
.mapToInt(x->x.getAge())
.fotEach(System.out::println);
并行流
// parallel() 开启并行流
// 或直接list.parallelStream()
// peek() 调试
Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9);
stream.parallel()
.peek(x->System.out.println(x+Thread.currentThread().getName()))
.filter(x->x>5)
.reduce((result,ele)->result+ele)
.get();