How to use Java 8 streams to find all values preceding a larger value?

后端 未结 6 867
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 18:57

Use Case

Through some coding Katas posted at work, I stumbled on this problem that I\'m not sure how to solve.

Using Java 8 Streams, given a

相关标签:
6条回答
  • 2020-12-29 19:31

    That's not a pure Java8, but recently I've published a small library called StreamEx which has a method exactly for this task:

    // Find all numbers where the integer preceded a larger value.
    Collection<Integer> numbers = Arrays.asList(10, 1, 15, 30, 2, 6);
    List<Integer> res = StreamEx.of(numbers).pairMap((a, b) -> a < b ? a : null)
        .nonNull().toList();
    assertEquals(Arrays.asList(1, 15, 2), res);
    

    The pairMap operation internally implemented using custom spliterator. As a result you have quite clean code which does not depend on whether the source is List or anything else. Of course it works fine with parallel stream as well.

    Committed a testcase for this task.

    0 讨论(0)
  • 2020-12-29 19:38

    Using IntStream.range:

    static List<Integer> findSmallPrecedingValues(List<Integer> values) {
        return IntStream.range(0, values.size() - 1)
            .filter(i -> values.get(i) < values.get(i + 1))
            .mapToObj(values::get)
            .collect(Collectors.toList());
    }
    

    It's certainly nicer than an imperative solution with a large loop, but still a bit meh as far as the goal of "using a stream" in an idiomatic way.

    Is it possible to retrieve the next value in a stream?

    Nope, not really. The best cite I know of for that is in the java.util.stream package description:

    The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.

    (Retrieving elements besides the current element being operated on would imply they could be visited more than once.)

    We could also technically do it in a couple other ways:

    • Statefully (very meh).
    • Using a stream's iterator is technically still using the stream.
    0 讨论(0)
  • 2020-12-29 19:43

    It's not a one-liner (it's a two-liner), but this works:

    List<Integer> result = new ArrayList<>();
    values.stream().reduce((a,b) -> {if (a < b) result.add(a); return b;});
    

    Rather than solving it by "looking at the next element", this solves it by "looking at the previous element, which reduce() give you for free. I have bent its intended usage by injecting a code fragment that populates the list based on the comparison of previous and current elements, then returns the current so the next iteration will see it as its previous element.


    Some test code:

    List<Integer> result = new ArrayList<>();
    IntStream.of(10, 1, 15, 30, 2, 6).reduce((a,b) -> {if (a < b) result.add(a); return b;});
    System.out.println(result);
    

    Output:

    [1, 15, 2]
    
    0 讨论(0)
  • 2020-12-29 19:44

    The accepted answer works fine if either the stream is sequential or parallel but can suffer if the underlying List is not random access, due to multiple calls to get.

    If your stream is sequential, you might roll this collector:

    public static Collector<Integer, ?, List<Integer>> collectPrecedingValues() {
        int[] holder = {Integer.MAX_VALUE};
        return Collector.of(ArrayList::new,
                (l, elem) -> {
                    if (holder[0] < elem) l.add(holder[0]);
                    holder[0] = elem;
                },
                (l1, l2) -> {
                    throw new UnsupportedOperationException("Don't run in parallel");
                });
    }
    

    and a usage:

    List<Integer> precedingValues = list.stream().collect(collectPrecedingValues());
    

    Nevertheless you could also implement a collector so thats works for sequential and parallel streams. The only thing is that you need to apply a final transformation, but here you have control over the List implementation so you won't suffer from the get performance.

    The idea is to generate first a list of pairs (represented by a int[] array of size 2) which contains the values in the stream sliced by a window of size two with a gap of one. When we need to merge two lists, we check the emptiness and merge the gap of the last element of the first list with the first element of the second list. Then we apply a final transformation to filter only desired values and map them to have the desired output.

    It might not be as simple as the accepted answer, but well it can be an alternative solution.

    public static Collector<Integer, ?, List<Integer>> collectPrecedingValues() {
        return Collectors.collectingAndThen(
                Collector.of(() -> new ArrayList<int[]>(),
                        (l, elem) -> {
                            if (l.isEmpty()) l.add(new int[]{Integer.MAX_VALUE, elem});
                            else l.add(new int[]{l.get(l.size() - 1)[1], elem});
                        },
                        (l1, l2) -> {
                            if (l1.isEmpty()) return l2;
                            if (l2.isEmpty()) return l1;
                            l2.get(0)[0] = l1.get(l1.size() - 1)[1];
                            l1.addAll(l2);
                            return l1;
                        }), l -> l.stream().filter(arr -> arr[0] < arr[1]).map(arr -> arr[0]).collect(Collectors.toList()));
    }
    

    You can then wrap these two collectors in a utility collector method, check if the stream is parallel with isParallel an then decide which collector to return.

    0 讨论(0)
  • 2020-12-29 19:45

    If you're willing to use a third party library and don't need parallelism, then jOOλ offers SQL-style window functions as follows

    System.out.println(
    Seq.of(10, 1, 15, 30, 2, 6)
       .window()
       .filter(w -> w.lead().isPresent() && w.value() < w.lead().get())
       .map(w -> w.value())
       .toList()
    );
    

    Yielding

    [1, 15, 2]
    

    The lead() function accesses the next value in traversal order from the window.

    Disclaimer: I work for the company behind jOOλ

    0 讨论(0)
  • 2020-12-29 19:47

    You can achieve that by using a bounded queue to store elements which flows through the stream (which is basing on the idea which I described in detail here: Is it possible to get next element in the Stream?

    Belows example first defines instance of BoundedQueue class which will store elements going through the stream (if you don't like idea of extending the LinkedList, refer to link mentioned above for alternative and more generic approach). Later you just examine the two subsequent elements - thanks to the helper class:

    public class Kata {
      public static void main(String[] args) {
        List<Integer> input = new ArrayList<Integer>(asList(10, 1, 15, 30, 2, 6));
    
        class BoundedQueue<T> extends LinkedList<T> {
          public BoundedQueue<T> save(T curElem) {
            if (size() == 2) { // we need to know only two subsequent elements
              pollLast(); // remove last to keep only requested number of elements
            }
    
            offerFirst(curElem);
            return this;
          }
    
          public T getPrevious() {
            return (size() < 2) ? null : getLast();
          }
    
          public T getCurrent() {
            return (size() == 0) ? null : getFirst();
          }
        }
    
        BoundedQueue<Integer> streamHistory = new BoundedQueue<Integer>();
    
        final List<Integer> answer = input.stream()
          .map(i -> streamHistory.save(i))
          .filter(e -> e.getPrevious() != null)
          .filter(e -> e.getCurrent() > e.getPrevious())
          .map(e -> e.getPrevious())
          .collect(Collectors.toList());
    
        answer.forEach(System.out::println);
      }
    }
    
    0 讨论(0)
提交回复
热议问题