Lambda

# 导读


  JDK8之后提供了链式写法,lambda给工作带来了很多方便,学会它会很大程度提升工作效率。

# 用法


  先构造原始数据,然后把orderList转换成map.订单id当做key,订单来源作为value;

@Data
public class Order {
    private String orderId;
    private String source;
}
1
2
3
4
5
# 构造方法1

final Map<String, String> map1 = orderList.stream().collect(Collectors.toMap(o -> o.getOrderId(), o -> o.getSource()));
final Map<String, String> map1 = orderList.stream().collect(Collectors.toMap(Order::getId, Order::getSource));
1
2

  出现Exception in thread "main" java.lang.IllegalStateException: Duplicate key pc;异常;原因在于Collectors.toMap没有传递第三个构造参数, 且第四个参数为HashMap,当往第四个返回参数中放入相同订单id的数据时,就会触发第三个构造参数抛出异常;

public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper) {
        return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}

 private static <T> BinaryOperator<T> throwingMerger() {
        return (u,v) -> { throw new IllegalStateException(String.format("Duplicate key %s", u)); };
 }
1
2
3
4
5
6
7
8
9
# 构造方法2

//第三个参数含义:把相同订单id的来源使用"_"按照list中的顺序连接成字符串
final Map<String, String> map2 = orderList.stream().collect(Collectors.toMap(o -> o.getOrderId(), o -> o.getSource(), (o1, o2) -> o1 + "_" + o2));
//含义:如果出现相同的订单id,value总是取第一个'订单来源'当做value
final Map<String, String> map2 = orderList.stream().collect(Collectors.toMap(o -> o.getOrderId(), o -> o.getSource(), (o1, o2) -> o1));

    //BinaryOperator合并操作
    public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper,
                                    BinaryOperator<U> mergeFunction) {
        return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
    }
    
    public interface BinaryOperator<T> extends BiFunction<T,T,T> 
    
@FunctionalInterface
public interface BiFunction<T, U, R> {

    /**
     * 处理类型T和U的参数,返回类型R
     * Applies this function to the given arguments.
     *
     * @param t the first function argument
     * @param u the second function argument
     * @return the function result
     */
    R apply(T t, U u);
}    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 构造方法3

  如果此时想按照订单的key的字母顺序排序(第三种构造函数),最后一个参数为Supplier接口,Represents a supplier of results.

   final Map<String, String> map3 = orderList.stream().collect(Collectors.toMap(o -> o.getOrderId(), o -> o.getSource(),
                (o1, o2) -> o1 + "_" + o2, TreeMap::new));
                
       public static <T, K, U, M extends Map<K, U>>
    Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
                                Function<? super T, ? extends U> valueMapper,
                                BinaryOperator<U> mergeFunction,
                                Supplier<M> mapSupplier) {
        BiConsumer<M, T> accumulator
                = (map, element) -> map.merge(keyMapper.apply(element),
                                              valueMapper.apply(element), mergeFunction);
        return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);
    }  

//重点:T:出参类型;没有入参;常用于业务“有条件运行”时,符合条件再调用获取结果的应用场景;运行结果须提前定义,但不运行
@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}           
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25