代码之家  ›  专栏  ›  技术社区  ›  JDC

Java Streams-如果存在比较器,则排序

  •  6
  • JDC  · 技术社区  · 8 年前

    我有一节课 Comparator


    比较器 是可选的,我必须评估它的存在并执行相同的流代码,或者 sorted() 或没有:

    if(comparator != null) {
        [...].stream().map()[...].sorted(comparator)[...];
    } else {
        [...].stream().map()[...];
    }
    

    问题:
    有没有更优雅的方法来做到这一点而不需要代码重复?

    注:
    比较器

    此外,元素已经在排序点映射,因此我无法以某种方式引用流的根列表,因为我不再有原始元素。

    5 回复  |  直到 8 年前
        1
  •  8
  •   Eran    8 年前

    你可以这样做:

    Stream<Something> stream = [...].stream().map()[...]; // preliminary processing
    if(comparator != null) {
        stream = stream.sorted(comparator); // optional sorting
    }
    stream... // resumed processing, which ends in some terminal operation (such as collect)
    
        2
  •  4
  •   fps    8 年前

    Optional :

    Stream<Whatever> stream = [...].stream().map()[...];
    
    List<WhateverElse> result = Optional.ofNullable(comparator)
        .map(stream::sorted)
        .orElse(stream)
        .[...] // <-- go on with the stream pipeline
        .collect(Collectors.toList());
    
        3
  •  2
  •   Boris van Katwijk    8 年前

     Comparator<E> NO_SORTING = (one, other) -> 0;
    

    .sorted(comparator.orElse(NO_SORTING))
    
        4
  •  1
  •   123-xyz    8 年前

    如果你不介意使用第三方图书馆 StreamEx

    StreamEx(source).[...].chain(s -> comparator == null ? s : s.sorted(comparator)).[...];
    
        5
  •  0
  •   user4910279 user4910279    8 年前

    您可以使用辅助功能来实现这一点。

    static <T, R> R applyFunction(T obj, Function<T, R> f) {
        return f.apply(obj);
    }
    

    applyFunction([...].stream().map()[...],
        stream -> comparator == null ? stream : stream.sorted(comparator))
        [...];
    

    您不需要知道中间流类型。