Java stream reduce

后端 未结 4 2538
南旧
南旧 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:34

    This is an alternative approach that uses slightly different data structures.

    If this is an option, changing from int[] to List allows for more flexibility (not to mention avoiding creating/copying arrays multiple times):

    class Tuple {
        Direction direction;
        List data;
    }
    

    And the following function does the merging on a Deque collection:

    private static List next(Deque t, Direction d) {
        if (!t.isEmpty() && t.peekLast().getDirection() == d) {
            return t.peekLast().getData();
        } else {
            Tuple next = new Tuple();
            next.direction = d;
            next.data = new ArrayList<>();
            t.addLast(next);
            return next.data;
        }
    }
    

    And with that, the stream can look as simple as:

    Deque deq = new LinkedList<>(); //the final collection of tuples
    
    tuples.stream()
    .flatMap(tp -> tp.getData().stream()
                     .map(d -> Pair.of(tp.getDirection(), Integer.valueOf(d))))
    .forEach(el -> next(deq, el.getLeft()).add(el.getRight()));
    

提交回复
热议问题