Java stream reduce

后端 未结 4 2564
南旧
南旧 2021-02-20 11:53

I have the following example data set that I want to transform / reduce using Java stream api based on direction\'s value

Direction    int[]
IN           1, 2
O         


        
4条回答
  •  一整个雨季
    2021-02-20 12:32

    I've got two ideas on this topic. First one is getting the indices like in this answer and group it accordingly.

    The second idea - if you already got a Stream a custom Collector should be used (similar to the other solutions, though using Deque):

    private Collector> squashTuples() {
      return new Collector, List>() {
        @Override
        public Supplier> supplier() {
          return ArrayDeque::new;
        }
    
        @Override
        public BiConsumer, Tuple> accumulator() {
          return (acc, e) -> {
            Objects.requireNonNull(e);
            if (!acc.isEmpty() && acc.peekLast().getDirection() == e.getDirection()) {
              acc.offerLast(acc.pollLast().merge(e));
            } else {
              acc.offerLast(e);
            }
          };
        }
    
        @Override
        public BinaryOperator> combiner() {
          return (left, right) -> {
            if (!left.isEmpty() && !right.isEmpty() && left.peekLast().getDirection() == right.peekFirst().getDirection()) {
              left.offerLast(left.pollLast().merge(right.pollFirst()));
            }
            left.addAll(right);
            return left;
          };
        }
    
        @Override
        public Function, List> finisher() {
          return ArrayList::new;
        }
    
        @Override
        public Set characteristics() {
          return EnumSet.noneOf(Characteristics.class);
        }
      };
    }
    

提交回复
热议问题