public class testB {
public static void main(String[] args) {
//函数式接口@FunctionalInterface
//lambda表达式必须依附于函数式接口而存在,以为java中lambda属于对象,是匿名内部类的简化
/**
* 四大核心函数式接口
* 1.消费型接口Consumer<T> public void accept(T);
* 2.供给型接口Supplier<T> public T get();
* 3.函数型接口Function<T,R> public R apply(T)
* 4.断言型接口Predicate<T> public boolean test(T)
*/
System.out.println("------------------------Consumer--------------------------------");
System.out.println();
Consumer<Double> con = m-> System.out.println("此次消费:"+m);
Consumer<Double> con2 =System.out::println;
con.accept(500.0);
con2.accept(1000.0);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------Supplier--------------------------------");
System.out.println();
Supplier<Integer> supplier = ()-> new Random().nextInt();
System.out.println(supplier.get());
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------Function--------------------------------");
System.out.println();
Function<String,String> function= s1->s1.toUpperCase();
Function<String,String> function2= String::toUpperCase;
System.out.println(function.apply("abcdefg"));
System.out.println(function2.apply("1234qwer"));
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------Predicate--------------------------------");
System.out.println();
List list = Arrays.asList("苍老师","布泽老师","麻生希博士","上原瑞橞博士");
Predicate<List<String>> predicate = lst->{
List newList = new ArrayList();
for (int i=0;i<lst.size();i++){
if (list.get(i).equals("苍老师")){
return true;
}
}
return false;
};
System.out.println(predicate.test(list));
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("----------------------方法引用----------------------------------");
/**
* 对象::实例方法
* 类::实例方法
* param1.aaa(param2) 类::aaa;
* class = param1.aaa();
* 类::静态方法
*/
System.out.println("------------------------Function--------------------------------");
System.out.println();
Consumer<String> con3 = System.out::println;
Supplier<String> supplier1 = new Student("maomao",18)::getName;
Comparator<Integer> comparator2 = Integer::compare;
Function<Double,Long> function1 = Math::round;
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------Function--------------------------------");
System.out.println();
Comparator<String> comparator = String::compareTo;
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------Function--------------------------------");
System.out.println();
BiPredicate<String,String> biPredicate = (s1,s2) -> s1.equals(s2);
BiPredicate<String,String> biPredicate1 = String::equals;
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------Function--------------------------------");
System.out.println();
Function<Student,String> function3 = Student::getName;
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("----------------------构造器引用和数组引用----------------------------------");
/**
* 对象::实例方法
* 类::实例方法
* param1.aaa(param2) 类::aaa;
* class = param1.aaa();
* 类::静态方法
*/
System.out.println("------------------------构造器--------------------------------");
System.out.println();
Supplier<Student> supplier2 = ()->new Student("aa",18);
Supplier<Student> supplier3 = Student::new;
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------构造器--------------------------------");
System.out.println();
Function<String,Student> function4 = Student::new;
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------构造器--------------------------------");
System.out.println();
BiFunction<String,Integer,Student> biFunction = Student::new;
System.out.println(biFunction.apply("张三",88).getName());
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------数组--------------------------------");
System.out.println();
Function<Integer,String []> function5 = len -> new String[len];
Function<Integer,String []> function6 = String []::new;
System.out.println(function6.apply(10).length);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("----------------------Strean流----------------------------------");
/**
* Stream定义在java.util.stream包下
* 作用:对集合数据进行处理:排序,筛选,映射
* Collection集合主要是将数据放在内存中,而stream是对这些内存中的数据做进一步的处理,stream本身不存储数据
* Stream对数据的操作分为三步:
* 1.创建Stream
* 2.对数据进行操作:属于懒加载,不会立即执行,只有当第三步提交操作执行了才会执行
* 3.提交操作
*/
System.out.println("----------------------创建Strean流有四种方式----------------------------------");
System.out.println("------------------------方式一:通过集合创建--------------------------------");
System.out.println();
List<Student> list1 = Student.getList();
//串行流
Stream<Student> stream1 = list.stream();
//并行流
Stream<Student> stream2 = list.parallelStream();
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------方式二:通过Arrays工具类的stream方法--------------------------------");
System.out.println();
int [] intarr = {11,22,33};
double [] duoblearr = {1.1,2.2,3.3};
long [] longarr = {1l,2l,3l};
Student [] stuarr = {new Student(),new Student()};
IntStream intStream = Arrays.stream(intarr);
DoubleStream doubleStream = Arrays.stream(duoblearr);
LongStream longStream = Arrays.stream(longarr);
Stream<Student> stuStream = Arrays.stream(stuarr);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------方式三:通过stream本身的of方法--------------------------------");
System.out.println();
Stream<Integer> integerStream = Stream.of(11,22,33,44);
Stream<Student> studentStream = Stream.of(new Student(),new Student());
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------方式四:通过无限流创建--------------------------------");
System.out.println();
//容器中的元素是无限的,Stream有两个方法:iterate和generate
//Unary表示一元的 UnaryOperation一元运算符
UnaryOperator<Integer> func = new UnaryOperator<Integer>() {
@Override
public Integer apply(Integer integer) {
return integer + 2;
}
};
//初始值为0,后面每次加2
Stream s1 = Stream.iterate(0,func);
Stream s2 = Stream.iterate(10,t->t+10);
Stream s3 = Stream.generate(Math::random);
s1.limit(10).forEach(System.out::println);
s2.limit(10).forEach(System.out::println);
s3.limit(10).forEach(System.out::println);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("----------------------Strean对数据的操作----------------------------------");
/**
* 筛选与分片
*/
System.out.println("------------------------1:filter(Predicate)从容器中把返回false的剔除--------------------------------");
System.out.println();
List<Student> list2 = Student.getList();
Stream<Student> stuStream2 = list2.stream();
//将list中年龄大于30的取出
Stream<Student> endStream = stuStream2.filter(stu->stu.getAge()>30);
endStream.forEach(System.out::println);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------2:limit(n)取出容器中前n个元素--------------------------------");
System.out.println();
List<Student> list3 = Student.getList();
Stream<Student> stuStream3 = list3.stream();
//将list中年龄大于30的取出
Stream<Student> stream3 = stuStream3.filter(stu -> stu.getAge()>1).limit(2);
stream3.forEach(System.out::println);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------3:skip(n) 跳过前n个数据,如果不足n个,则返回一个空流,也就是流中没有任何数据--------------------------------");
System.out.println();
List<Student> list4 = Student.getList();
Stream<Student> stuStream4 = list4.stream();
//将list中年龄大于30的取出
Stream<Student> stream4 = stuStream4.filter(stu -> stu.getAge()>1).skip(2);
stream4.forEach(System.out::println);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------3:distinct() 去重:根据equals方法进行去重--------------------------------");
System.out.println();
List<Student> list5 = Student.getList();
//@data注解会自动重写对象的equals方法和hashcode方法
list5.add(new Student("abc",222));
list5.add(new Student("abc",222));
list5.add(new Student("abc",222));
list5.add(new Student("abc",222));
list5.add(new Student("abc",222));
list5.add(new Student("abc",222));
Stream<Student> stuStream5 = list5.stream();
//将list中年龄大于30的取出
Stream<Student> stream5 = stuStream5.distinct();
stream5.forEach(System.out::println);
System.out.println();
System.out.println("--------------------------------------------------------");
Student ss1 = new Student();
Student ss2 = new Student();
System.out.println(ss1.equals(ss2));
System.out.println(ss1.hashCode() == ss2.hashCode());
/**
* 映射
*/
System.out.println("------------------------map(Function f):将流中的每个元素使用function处理后,将function的返回值构成新的流--------------------------------");
Stream<String> arrList = Arrays.stream(new String []{"aa","bb","cc"});
//将数组中的元素全部转换成大写
arrList.map(String::toUpperCase).forEach(System.out::println);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------map(Function f):将流中的每个元素使用function处理后,将function的返回值构成新的流--------------------------------");
//获取学生姓名大于三个字的
List<Student> list6 = Student.getList();
Stream<Student> stream = list6.stream();
stream.map(stu -> {if (stu.getName().length()>3){return stu;}return null;}).forEach(System.out::println);
Stream<Student> stream6 = list6.stream();
Stream<String> stringStream = stream6.map(Student::getName);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------flatMap(Function f):将流中的每个元素使用function处理后,将function的返回值构成新的流--------------------------------");
//map和flatMap的区别:如果操作的本身是流数据,Map会把流装到外面的流里面形成Stream<Stream<T>>结构,也就是说它会把流对象当成一个整体,不会理会流里面的内容
// 如果是flatMap,会把里面的流数据和外面的流数据合并成一个流,形参Stream<T>的结构 ,会将流里面的数据取出一一处理
//用list的add和andall方法举例
//add方法就好像map方法一样
List lista = Arrays.asList(11,22);
List listb = Arrays.asList(33,44);
List listc = new ArrayList<>();
listc.add(lista);
listc.add(listb);
System.out.println(listc.toString());//[ [11, 22], [33, 44] ]
System.out.println();
System.out.println("--------------------------------------------------------");
//addAll就相当于flatMap
List listd = new ArrayList<>();
listd.addAll(lista);
listd.addAll(listb);
System.out.println(listd.toString());// [11, 22, 33, 44]
System.out.println();
System.out.println("--------------------------------------------------------");
List<String> list7 = Arrays.asList("abcdef");
Stream<String> stream7 = list7.stream();
Stream<Stream<Character>> stream8 = stream7.map(str -> {
char[] chars = str.toCharArray();
List<Character> lists = new ArrayList();
for (Character ch:chars){
lists.add(ch);
}
return lists.stream();
});
stream8.forEach(ss->ss.forEach(System.out::println));
Stream<String> stream77 = list7.stream();
Stream<Character> stream88 = stream77.flatMap(str -> {
char[] chars = str.toCharArray();
List<Character> lists = new ArrayList();
for (Character ch:chars){
lists.add(ch);
}
return lists.stream();
});
stream88.forEach((System.out::println));
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("--------------------------排序------------------------------");
System.out.println("------------------------sorted()自然排序--------------------------------");
System.out.println();
List<Integer> inlist = Arrays.asList(12,66,14,78,33,66,11);
inlist.stream().sorted().forEach(System.out::println);
List<Student> sslist = Student.getList();
//会报错,因为我们的Student类并没有实现Comparable接口
//sslist.stream().sorted().forEach(System.out::println);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------sorted(Comparator)自定义排序--------------------------------");
System.out.println();
//要么实现comparable接口,要么重写Comparator
sslist.stream().sorted((sss1,sss2) -> { return Integer.compare(sss1.getAge(),sss2.getAge());}).forEach(System.out::println);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("--------------------------Stream流的提交操作------------------------------");
/**
* Stream对没有提交前所有的操作并未生效执行,只有执行提交操作后所有的操作才会执行,
* 提交之后Stream流会关闭
* 下面是对流进行提交操作的方法
*
* 提交操作有三种:匹配与查找、规约、收集
*/
System.out.println("------------------------匹配与查找--------------------------------");
System.out.println();
//allMatch(Predicate) 检查是否匹配所有元素
List<Student> list8 = Student.getList();
Stream<Student> stream9 = list8.stream();
boolean b = stream9.allMatch((stu) -> { return stu.getAge()>8;});
System.out.println("是否所有都匹配:"+b);
//anyMatch(Predicate) 是否至少有一条匹配
Stream<Student> stream11 = list8.stream();
boolean b1 = stream11.anyMatch(stu -> stu.getAge() > 30);
System.out.println("是否有一个匹配:"+b1);
//noneMathce(Predicate)检查是否 没有 匹配的元素 注意是检查是否没有 ,没有返回true
Stream<Student> stream12 = list8.stream();
boolean b2 = stream12.noneMatch(stu -> stu.getAge() > 300);
System.out.println("是否没有一个超过300的:"+b2);
//findFirst返回第一个元素
Stream<Student> stream13 = list8.stream();
System.out.println(stream13.findFirst());
//findAny返回当前流中的任意元素
Stream<Student> stream14 = list8.stream();
System.out.println(stream14.findAny());
//count 返回流中的元素总数
Stream<Student> stream15 = list8.stream();
System.out.println(stream15.count());
//max(Comparator) 返回流中最大值
Stream<Student> stream16 = list8.stream();
System.out.println(stream16.max((stu1,stu2)->{ return Integer.compare(stu1.getAge(),stu2.getAge());}));
//forEach(Consumer c) 内部迭代所有元素
Stream<Student> stream17 = list8.stream();
stream17.forEach(System.out::println);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------规约---累计计算--------------------------------");
System.out.println();
//reduce(T,BinaryOperator) ,如果不给初始值,就以第一个值为初始值
//public interface BinaryOperator<T> extends BiFunction<T,T,T> { 传递两个同类型的参数,返回值还是同一类型
//10作为起始值,然后累加集合中的数
List<Integer> listp = Arrays.asList(1,2,3,4);
System.out.println(listp.stream().reduce(10, (num1, num2) -> num1 + num2));
Integer reduce2 = listp.stream().reduce(10, (num1, num2) -> num1 * num2);
System.out.println(reduce2);
System.out.println();
System.out.println("--------------------------------------------------------");
System.out.println("------------------------收集:将流中的数据存储到新的容器中--------------------------------");
System.out.println();
//collect(Collector c) 将Stream流中的数据转换到其他容器中 其中Collerctor
// 可由Collectors的静态方法获取
List<Student> collect = list8.stream().collect(Collectors.toList());
collect.forEach(System.out::println);
Set<Student> collect1 = list8.stream().collect(Collectors.toSet());
collect1.forEach(System.out::println);
System.out.println();
System.out.println("--------------------------------------------------------");
/**
* # 八:Optional类
* Optional<T>类是java.util下面的一个容器类,可以包装其他对象并且可以避免空指针
*/
System.out.println("------------------------创建Optional对象--------------------------------");
System.out.println();
//Optional.of(T t) 必须非空
Student stu = new Student();
Optional<Student> stu1 = Optional.of(stu);
System.out.println(stu1);
//会报NullPoint,所以此方法没什么用
//Optional<Object> o = Optional.of(null);
//System.out.println(o);
//Optonal.empty() 创建一个空格的Optional实例
Optional<Object> empty = Optional.empty();
System.out.println(empty);
//Optional.ofNullable(T t) t可以为null,如果为null,Optional就是empty
Optional<Object> o2 = Optional.ofNullable(null);
System.out.println(o2);
//orElse 有则获取,没有则给出默认值
//stu = null;
stu.setName("霸王超过");
Optional<Student> optional = Optional.ofNullable(stu);
Student student = optional.orElse(new Student());
System.out.println(student);
//isPresent,先判断是否为空,再进行获取
//stu = null;
Optional optional1 = Optional.ofNullable(stu);
if (optional1.isPresent()){
System.out.println(stu.getName());
}else{
System.out.println("此对象为空");
}
System.out.println();
System.out.println("--------------------------------------------------------");
}
}
JDK8新特性
最新推荐文章于 2022-10-29 21:58:50 发布