jdk 8,stream(groupBy ,reduce ,optional, sorted的用法)

1, 函数式编程

lambda 是一个接口的方法,省略了接口的书写,函数式接口就是只定义一个抽象方法的接口runable就是一个函数式接口

public static void process(Runnable r){
        r.run();
    }
public static void main(String args[]){
     Runnable r1 = () -> System.out.println("Hello World 1");
     Runnable r2 = new Runnable(){
      
     public void run(){
           System.out.println("Hello World 2");
         }
     };
     process(r1);
     process(r2);
     process(() -> System.out.println("Hello World 3"));
 }

java.util.function.Predicate<T>接口定义了一个名 test的抽象方法,它接受一份 T类型的对象,并返回一个boolean

2, stream调用了toMap()方法,可能生成map的key有重复的情况

 将java数组转化为stream流时,如果stream调用了toMap()方法,可能生成map的key有重复的情况。

//如果key值有重复,那么方法会抛异常(duplic.. key excption)
Stream.of(emps).collect(Collectors.toMap(Emp::getId, Emp::getName);
//改写成以下方式,针对重复key的  覆盖之前的value
Stream.of(emps).collect(Collectors.toMap(Emp::getId, Emp::getName,(k,v)->v));

3, stream流处理

1, java 8中的流处理debug方法

 List<Integer> numbers = new ArrayList<Integer>();
 numbers.add(1);numbers.add(2);numbers.add(3);numbers.add(4);
 List<Integer> result = numbers.stream()
         .peek(x -> System.out.println("from stream: " + x))
         .map(x -> x + 17)
         .peek(x -> System.out.println("after map: " + x))
         .filter(x -> x % 2 == 0)
         .peek(x -> System.out.println("after filter: " + x))
         .limit(3)
         .peek(x -> System.out.println("after limit: " + x))
         .collect(toList());
//output
from stream: 1
after map: 18
after filter: 18
after limit: 18
from stream: 2
after map: 19
from stream: 3
after map: 20
after filter: 20
after limit: 20
from stream: 4
after map: 21

使用peek查看Stream流水线中的数据流的值 通过peek操作我们能清楚地了解流水线操作中每一步的输出结果,可以用来debug。

从结果中可以看到stream的map,filter ,limit 方法都是延迟加载的,调用这些方法时只是先做个记录,程序直到执行到collect的方法时,才会正式对stream流进行所有方法操作。所以”from stream“这个语句是隔开执行(隔开打印的)。

 

2,groupBy的用法

//将saleList按照相同时间,平台,种类进行分组,结果是相同时间,相同平台,相同种类的sale对象会放在同一个List里。返回的map的keys是‘s.getStDate() + '_'....’这一串
,values是一个list。
Map<String,List<Sales>> trendMap = salesList.stream().collect(Collectors.groupingBy(
                s -> s.getStDate() + "_" + s.getPlatform() + "_" + s.getCategoryId()));

  

3,reduce的用法,将a对象和b对象进行相加的操作

Optional<Sales> optional = childList.stream().reduce((a,b) -> {
                a.setRealPrice(a.getRealPrice().add(b.getRealPrice()));
                a.setSaleAmount(a.getSaleAmount() + b.getSaleAmount());
                return a;
            });
//如果optional不为null,那么调用saleListTotal.add()的方法
optional.ifPresent(salesListTotal::add);

/**
 * If a value is present, invoke the specified consumer with the value,
 * otherwise do nothing.
 *
 * @param consumer block to be executed if a value is present
 * @throws NullPointerException if value is present and {@code consumer} is
 * null
 */
public void ifPresent(Consumer<? super T> consumer) {
    if (value != null)
        consumer.accept(value);
}

4,sorted方法的用法

salesListTotal=salesListTotal.stream().sorted(Comparator.comparing(Sales::getCategoryId)).collect(Collectors.toList());

  


原文地址:https://www.cnblogs.com/yanyuechao/p/8372840.html