java8实战

2021-10-31  本文已影响0人  sundern

Stream API

//按年龄升序
.sorted(Comparator.comparing(Student::getAge))
//按年龄降序
.sorted(Comparator.comparing(Student::getAge).reversed())
public void sortUserInfoList(List<UserInfo> userInfoList){
       userInfoList.sort((user1, user2) -> {
           Long userId1 = user1.getUserId();
           Long userId2 = user2.getUserId();
           return userId1.compareTo(userId2);
       });
 }
word = ["Hello","World"]
map(word->word.split("")) ~~~~~{[H,e,l,l,o],[W,o,r,l,d]} 
//降维扁平化
flatMap(word->word.split(""))~~~~~{H,e,l,l,o,W,o,r,l,d} 
//集合转list
.collect(Collectors.toList())
//集合转set
.collect(Collectors.toSet())
//集合转map
.collect(Collectors.toMap(a->a,b->b))
//没有值相等时返回true
boolean cc = strs.stream().noneMatch(str -> str.equals("a"));

IntStream | DoubleStream | LongStream:数值流

//构建IntStream,使用builder并单个添加元素
  IntStream intStream = IntStream.builder().add(1).build();

//无限流 和limit连用
  intStream = IntStream.generate(()-> (int) (Math.random()*10000));
  intStream = intStream.limit(5);

//迭代无限流 和limit连用
  intStream = IntStream.iterate(2,n->n*3);
  intStream = intStream.limit(5);

//of方法把一组值变成流
  intStream = IntStream.of(1,2,3);

//两个数之间的整数流 左闭右开
  intStream = IntStream.range(1,5);

//两个数之间的整数流 全闭 跳过前2个
  intStream = IntStream.rangeClosed(1,5).skip(2);

//将两个流合并为一个
  IntStream otherIntStream = IntStream.of(1,2,3);
  intStream = IntStream.concat(intStream,otherIntStream);
//循环遍历
intStream.forEach(System.out::println);

//升序遍历
intStream.sorted().forEach(System.out::println);

//降序 先要用boxed方法转成包装类型
intStream.boxed().sorted(Comparator.reverseOrder()).forEach(System.out::println);

//peek操作流返回值仍为IntStream,只有关闭流时才会执行
System.out.println(intStream.peek(System.out::println).sum());
//流转数组
int[] array = intStream.toArray();
System.out.println(array);

//转double流,long流同理
DoubleStream doubleStream = intStream.asDoubleStream();
doubleStream.forEach(System.out::println);

//映射为double流
DoubleStream doubleStream =intStream.mapToDouble(i->i);
doubleStream.forEach(System.out::println);
//计数
long count = intStream.count();
System.out.println(count);

//求和
int sum = intStream.sum();
System.out.println(sum);

//规约
int reduce = intStream.reduce(0,(a,b)->a+b);
System.out.println(reduce);

并行流

//iterator得到的流串行效率高
LongStream.iterate(1L,i -> i+1).limit(10000000L).parallel().reduce(0L,Long:sum)

//range得到得流并行效率高
LongStream.range(0L, 100000000L).parallel().reduce(0L,Long::sum);

lambda

//实现Runnable接口
new Thread(()-> System.out.println("hello,world!")).start();

//实现Comparator接口
Collections.sort(list,(a,b)->a.charAt(0)>b.charAt(0)?1:-1);
//Predicate<T>,对参数进行预测,返回true|false
String name = "zhoupei";
Predicate<String> predicate = s -> name.equals(s);
list.stream().filter(predicate);

//Consumer<T>,对参数执行无返回值的回调
private static void execute(Consumer consumer){
  String name = "zhoupei";
  System.out.println("执行任务");
  consumer.accept(name);
}
execute(s-> System.out.println("回调打印我的名字:" + s));

//Function<T,R>,对参数执行有返回值的回调
Function<Integer,Integer> function = i-> 1*5;
System.out.println(function.apply(3));

方法引用

//调用类的静态方法
ClassName::staticMethod

//引用对象的方法
String:length

//调用已经存在的外部对象的方法
Transaction::getValue

实践案例

List<String> list1 = new ArrayList<String>(){{
    add("lisi");
    add("wangwu");
}};
List<String> list2 = new ArrayList<String>(){{
    add("zhangsan");
    add("lisi");
    add("wangwu");
}};
list1.forEach(s1->list2.forEach(s2->{
    if (s1.equals(s2)){
      System.out.println(s2);
    }
}));

Optional

Optional<String> optional = Optional.ofNullable("hello world");
optional.ifPresent(s -> System.out.println(true));
String string = Optional.ofNullable("hello world").orElse("default");
String string = Optional.ofNullable("hello world").orElseGet(()->"default");
boolean exists = optional.filter(predicate1.and(predicate2)).isPresent();
optional.filter(predicate1.and(predicate2)).ifPresent(s-> System.out.println(true));
Predicate<String> predicate3 = s->"helloworld".equals(s);
optional.map(s -> s.replace(" ",""))
    .filter(predicate1.and(predicate2).and(predicate3))
    .ifPresent(s-> System.out.println(true));

--各种复合:比较器复合、谓词复合、函数复合(待充电)

上一篇 下一篇

猜你喜欢

热点阅读